package com.stylefeng.guns.modular.system.controller.util;
|
|
import com.google.common.collect.Lists;
|
import org.apache.http.Consts;
|
import org.apache.http.HttpEntity;
|
import org.apache.http.HttpStatus;
|
import org.apache.http.client.config.RequestConfig;
|
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpPost;
|
import org.apache.http.client.methods.HttpUriRequest;
|
import org.apache.http.client.protocol.HttpClientContext;
|
import org.apache.http.conn.ConnectTimeoutException;
|
import org.apache.http.entity.ContentType;
|
import org.apache.http.entity.StringEntity;
|
import org.apache.http.entity.mime.MultipartEntityBuilder;
|
import org.apache.http.entity.mime.content.FileBody;
|
import org.apache.http.entity.mime.content.StringBody;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
import org.apache.http.message.BasicNameValuePair;
|
import org.apache.http.util.EntityUtils;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.stereotype.Component;
|
|
import java.io.*;
|
import java.net.SocketTimeoutException;
|
import java.net.URI;
|
import java.nio.charset.StandardCharsets;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.stream.Collectors;
|
|
@Component
|
public class HttpUtils {
|
|
private Logger log = LoggerFactory.getLogger(this.getClass());
|
|
private final static String KEY = "7589cb21f09f6ab1a1263ca98f0b4d52";
|
|
//请求超时时间
|
private final static Integer TIME_OUT = 1000;
|
//http连接池
|
private static volatile PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
|
//请求配置
|
private static RequestConfig requestConfig;
|
|
public static PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManager() {
|
if (poolingHttpClientConnectionManager == null) {
|
synchronized (HttpUtils.class) {
|
if (poolingHttpClientConnectionManager == null) {
|
poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
|
//连接池最大连接数
|
poolingHttpClientConnectionManager.setMaxTotal(1024);
|
//每个路由最大连接数
|
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(32);
|
|
//配置请求的超时设置
|
requestConfig =
|
RequestConfig.custom().setConnectionRequestTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).setSocketTimeout(TIME_OUT).build();
|
}
|
}
|
}
|
return poolingHttpClientConnectionManager;
|
}
|
|
public static CloseableHttpClient getHttpClient() {
|
return HttpClients.custom().setConnectionManager(getPoolingHttpClientConnectionManager()).setDefaultRequestConfig(requestConfig).build();
|
}
|
|
/**
|
* 请求发送执行
|
*
|
* @param httpMethd
|
* @return
|
*/
|
public String registRequest(HttpUriRequest httpMethd) {
|
CloseableHttpClient httpClient = getHttpClient();
|
CloseableHttpResponse httpResponse = null;
|
try {
|
httpResponse = httpClient.execute(httpMethd, HttpClientContext.create());
|
int statusCode = httpResponse.getStatusLine().getStatusCode();
|
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
|
log.error("响应失败 statusCode {}", statusCode);
|
httpMethd.abort();
|
}
|
log.debug("响应成功 statusCode {}", statusCode);
|
String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
|
log.debug("响应成功 response {}", response);
|
return response;
|
} catch (ConnectTimeoutException e) {
|
throw new RuntimeException("接口超时");
|
} catch (SocketTimeoutException e) {
|
throw new RuntimeException("读取接口数据超时");
|
} catch (IOException e) {
|
throw new RuntimeException("接口请求失败,请尝试检查网络环境或请求接口是否能正常访问");
|
} finally {
|
// 关闭响应
|
try {
|
if (httpResponse != null) {
|
httpResponse.close();
|
}
|
// 关闭连接
|
//httpClient.close();
|
} catch (IOException e) {
|
throw new RuntimeException("关闭流异常:IOException");
|
}
|
}
|
}
|
|
/**
|
* 请求发送执行
|
*
|
* @param url
|
* @return
|
*/
|
public String registRequest(String url, File file) {
|
CloseableHttpClient httpClient = HttpClients.createDefault();
|
CloseableHttpResponse httpResponse = null;
|
try {
|
HttpPost httpPost = new HttpPost(url);
|
RequestConfig requestConfig = RequestConfig.custom()
|
.setSocketTimeout(10000)
|
.setConnectTimeout(5000)
|
.build();
|
httpPost.setConfig(requestConfig);
|
HttpEntity entity = MultipartEntityBuilder.create().addPart("img", new FileBody(file)).build();
|
httpPost.setEntity(entity);
|
httpResponse = httpClient.execute(httpPost);
|
int statusCode = httpResponse.getStatusLine().getStatusCode();
|
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
|
log.error("响应失败 statusCode {}", statusCode);
|
httpPost.abort();
|
}
|
log.debug("响应成功 statusCode {}", statusCode);
|
String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
|
log.debug("响应成功 response {}", response);
|
return response;
|
} catch (ConnectTimeoutException e) {
|
throw new RuntimeException("接口超时");
|
} catch (SocketTimeoutException e) {
|
throw new RuntimeException("读取接口数据超时");
|
} catch (IOException e) {
|
throw new RuntimeException("接口请求失败,请尝试检查网络环境或请求接口是否能正常访问");
|
} finally {
|
// 关闭响应
|
try {
|
if (httpResponse != null) {
|
httpResponse.close();
|
}
|
// 关闭连接
|
httpClient.close();
|
} catch (IOException e) {
|
throw new RuntimeException("关闭流异常:IOException");
|
}
|
}
|
}
|
|
/**
|
*
|
* @param type
|
* @param file
|
* @return
|
* @throws Exception
|
*/
|
public String ocr(String type, File file){
|
CloseableHttpClient httpClient = HttpClients.createDefault();
|
CloseableHttpResponse response = null;
|
String result = null;
|
// HttpClient请求的相关设置,可以不用配置,用默认的参数,这里设置连接和超时时长(毫秒)
|
RequestConfig config = RequestConfig.custom().setConnectTimeout(30000).setSocketTimeout(30000).build();
|
try {
|
HttpPost httppost = new HttpPost("http://v.juhe.cn/certificates/query");
|
// FileBody封装File类型的参数
|
FileBody bin = new FileBody(file);
|
// StringBody封装String类型的参数
|
StringBody keyBody = new StringBody(KEY, ContentType.TEXT_PLAIN);
|
StringBody typeBody = new StringBody(type, ContentType.TEXT_PLAIN);
|
// addPart将参数传入,并指定参数名称
|
HttpEntity reqEntity = MultipartEntityBuilder.create()
|
.addPart("pic", bin).addPart("key", keyBody)
|
.addPart("cardType", typeBody).build();
|
httppost.setEntity(reqEntity);
|
httppost.setConfig(config);
|
// 执行网络请求并返回结果
|
response = httpClient.execute(httppost);
|
HttpEntity resEntity = response.getEntity();
|
if (resEntity != null) {
|
result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
|
}
|
EntityUtils.consume(resEntity);
|
} catch (Exception e) {
|
throw new RuntimeException("接口请求失败,请尝试检查网络环境或请求接口是否能正常访问"+":"+e);
|
} finally {
|
try {
|
response.close();
|
httpClient.close();
|
} catch (IOException e) {
|
throw new RuntimeException("流关闭失败!"+":"+e);
|
}
|
}
|
// 得到的是JSON类型的数据需要第三方解析JSON的jar包来解析
|
return result;
|
}
|
|
// 此方法是把传进的字节流转化为相应的字符串并返回,此方法一般在网络请求中用到
|
public static String ConvertStreamToString(InputStream is, String charset)
|
throws Exception {
|
StringBuilder sb = new StringBuilder();
|
try (InputStreamReader inputStreamReader = new InputStreamReader(is,charset)) {
|
try (BufferedReader reader = new BufferedReader(inputStreamReader)) {
|
String line = null;
|
while ((line = reader.readLine()) != null) {
|
sb.append(line).append("\r\n");
|
}
|
}
|
}
|
return sb.toString();
|
}
|
|
public List<BasicNameValuePair> toPairs(Map<String, Object> params) {
|
List<BasicNameValuePair> pairs = Lists.newArrayList();
|
if (params != null && !params.isEmpty()) {
|
pairs = params.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(),
|
entry.getValue().toString())).collect(Collectors.toList());
|
}
|
return pairs;
|
}
|
|
/**
|
* get url请求
|
*
|
* @param url
|
* @return
|
*/
|
public String get(String url) {
|
HttpGet request = new HttpGet();
|
try {
|
request.setURI(new URI(url));
|
return registRequest(request);
|
} catch (Exception e) {
|
log.error("请求失败", e);
|
}
|
return null;
|
}
|
|
/**
|
* PSOT URL方式提交
|
*
|
* @param url 请求url
|
* @param params 请求参数
|
* @return
|
*/
|
public String postFromUrl(String url, Map<String, Object> params) {
|
HttpPost request = new HttpPost(url);
|
RequestConfig requestConfig = RequestConfig.custom()
|
.setSocketTimeout(10000)
|
.setConnectTimeout(5000)
|
.build();
|
request.setConfig(requestConfig);
|
request.setEntity(new UrlEncodedFormEntity(toPairs(params), Consts.UTF_8));
|
return registRequest(request);
|
}
|
|
/**
|
* PSOT JSON方式提交
|
*
|
* @param url 请求url
|
* @param params json串
|
* @return
|
*/
|
public String postFromJson(String url, String params) {
|
HttpPost request = new HttpPost(url);
|
request.setHeader("Content-type", "application/json");
|
request.setHeader("Accept", "application/json");
|
RequestConfig requestConfig = RequestConfig.custom()
|
.setSocketTimeout(8000)
|
.setConnectTimeout(6000)
|
.build();
|
request.setConfig(requestConfig);
|
StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8);
|
entity.setContentType("application/json");
|
request.setEntity(entity);
|
try {
|
return registRequest(request);
|
} catch (Exception e) {
|
log.error("请求失败", e);
|
}
|
return null;
|
}
|
}
|