工具类HttpClientPoolUtil,用以执行http请求
public class HttpClientPoolUtil {
// 日志
private static Logger logger = LoggerFactory.getLogger(HttpClientPoolUtil.class);
// httpClient连接池管理器
public static PoolingHttpClientConnectionManager cm = null;
// httpClient
public static CloseableHttpClient httpClient = null;
/**
* 默认content 类型
*/
private static final String DEFAULT_CONTENT_TYPE = "application/json";
/**
* 默认请求超时时间30s
*/
private static final int DEFAUL_TTIME_OUT = Integer.parseInt(PropertiesHander.getPropertiesValue("Http_Default_Timeout"));
// 最大路由连接数
private static final int count = Integer.parseInt(PropertiesHander.getPropertiesValue("defaultMaxPerRoute"));
// 最大连接请求数
private static final int totalCount = Integer.parseInt(PropertiesHander.getPropertiesValue("maxTotal"));
private static final int Http_Default_Keep_Time = Integer.parseInt(PropertiesHander.getPropertiesValue("Http_Default_Keep_Time"));
/**
* 初始化连接池
*/
public static synchronized void initPools() {
if (httpClient == null) {
cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(count);
cm.setMaxTotal(totalCount);
httpClient = HttpClients.custom().setKeepAliveStrategy(defaultStrategy).setConnectionManager(cm).build();
}
}
/**
* Http connection keepAlive 设置
*/
public static ConnectionKeepAliveStrategy defaultStrategy = new ConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
int keepTime = Http_Default_Keep_Time;
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (Exception e) {
e.printStackTrace();
logger.error("format KeepAlive timeout exception, exception:" + e.toString());
}
}
}
return keepTime * 1000;
}
};
public static CloseableHttpClient getHttpClient() {
return httpClient;
}
public static PoolingHttpClientConnectionManager getHttpConnectionManager() {
return cm;
}
/**
* 执行http post请求 默认采用Content-Type:application/json,Accept:application/json
*
* @param uri 请求地址
* @param data 请求数据
* @return
*/
public static String execute(String uri, String data,String headerKey,String headerValue) {
long startTime = System.currentTimeMillis();
HttpEntity httpEntity = null;
HttpEntityEnclosingRequestBase method = null;
String responseBody = "";
try {
if (httpClient == null) {
initPools();
}
method = (HttpEntityEnclosingRequestBase) getRequest(uri, HttpPost.METHOD_NAME, DEFAULT_CONTENT_TYPE, 0);
if(StringUtils.isNotEmpty(data)) {
method.setEntity(new StringEntity(data,"UTF-8"));
}
method.addHeader(headerKey, headerValue);
HttpContext context = HttpClientContext.create();
CloseableHttpResponse httpResponse = httpClient.execute(method, context);
httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
responseBody = EntityUtils.toString(httpEntity, "UTF-8");
/*
* String metype = httpEntity.getContentType().toString();
* if(metype.contains("application/json")) { responseBody =
* responseBody.replaceAll("\\\"",""); responseBody =
* responseBody.replaceAll("\\\\","\""); }
*/
}
} catch (Exception e) {
if(method != null){
method.abort();
}
e.printStackTrace();
logger.error(
"execute post request exception, url:" + uri + ", exception:" + e.toString() + ", cost time(ms):"
+ (System.currentTimeMillis() - startTime));
} finally {
if (httpEntity != null) {
try {
EntityUtils.consumeQuietly(httpEntity);
} catch (Exception e) {
e.printStackTrace();
logger.error(
"close response exception, url:" + uri + ", exception:" + e.toString() + ", cost time(ms):"
+ (System.currentTimeMillis() - startTime));
}
}
}
return responseBody;
}
public static String executeFormData(String uri, List<NameValuePair> pairs) {
long startTime = System.currentTimeMillis();
HttpEntity httpEntity = null;
HttpEntityEnclosingRequestBase method = null;
String responseBody = "";
try {
if (httpClient == null) {
initPools();
}
method = (HttpEntityEnclosingRequestBase) getRequest(uri, HttpPost.METHOD_NAME, "application/x-www-form-urlencoded", 0);
if(CollectionUtils.isNotEmpty(pairs)) {
method.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
}
HttpContext context = HttpClientContext.create();
CloseableHttpResponse httpResponse = httpClient.execute(method, context);
httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
responseBody = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (Exception e) {
if(method != null){
method.abort();
}
e.printStackTrace();
logger.error(
"execute post request exception, url:" + uri + ", exception:" + e.toString() + ", cost time(ms):"
+ (System.currentTimeMillis() - startTime));
} finally {
if (httpEntity != null) {
try {
EntityUtils.consumeQuietly(httpEntity);
} catch (Exception e) {
e.printStackTrace();
logger.error(
"close response exception, url:" + uri + ", exception:" + e.toString() + ", cost time(ms):"
+ (System.currentTimeMillis() - startTime));
}
}
}
return responseBody;
}
/**
* 执行http post请求 默认采用Content-Type:application/json,Accept:application/json
*
* @param uri 请求地址
* @param data 请求数据
* @return
*/
public static String execute(String uri, String data) {
long startTime = System.currentTimeMillis();
HttpEntity httpEntity = null;
HttpEntityEnclosingRequestBase method = null;
String responseBody = "";
try {
if (httpClient == null) {
initPools();
}
method = (HttpEntityEnclosingRequestBase) getRequest(uri, HttpPost.METHOD_NAME, DEFAULT_CONTENT_TYPE, 0);
if(StringUtils.isNotEmpty(data)) {
method.setEntity(new StringEntity(data,"UTF-8"));
}
HttpContext context = HttpClientContext.create();
CloseableHttpResponse httpResponse = httpClient.execute(method, context);
httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
responseBody = EntityUtils.toString(httpEntity, "UTF-8");
/*
* String metype = httpEntity.getContentType().toString();
* if(metype.contains("application/json")) { responseBody =
* responseBody.replaceAll("\\\"",""); responseBody =
* responseBody.replaceAll("\\\\","\""); }
*/
}
} catch (Exception e) {
if(method != null){
method.abort();
}
e.printStackTrace();
logger.error(
"execute post request exception, url:" + uri + ", exception:" + e.toString() + ", cost time(ms):"
+ (System.currentTimeMillis() - startTime));
} finally {
if (httpEntity != null) {
try {
EntityUtils.consumeQuietly(httpEntity);
} catch (Exception e) {
e.printStackTrace();
logger.error(
"close response exception, url:" + uri + ", exception:" + e.toString() + ", cost time(ms):"
+ (System.currentTimeMillis() - startTime));
}
}
}
return responseBody;
}
/**
* 执行http post请求 默认采用Content-Type:application/json,Accept:application/json
*text/xml
* @param uri 请求地址
* @param data 请求数据
* @return
*/
public static String executeText(String uri, String data) {
long startTime = System.currentTimeMillis();
HttpEntity httpEntity = null;
HttpEntityEnclosingRequestBase method = null;
String responseBody = "";
try {
if (httpClient == null) {
initPools();
}
method = (HttpEntityEnclosingRequestBase) getRequest(uri, HttpPost.METHOD_NAME, "text/plain", 0);
if(StringUtils.isNotEmpty(data)) {
method.setEntity(new StringEntity(data,"UTF-8"));
}
HttpContext context = HttpClientContext.create();
CloseableHttpResponse httpResponse = httpClient.execute(method, context);
httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
responseBody = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (Exception e) {
if(method != null){
method.abort();
}
e.printStackTrace();
logger.error(
"execute post request exception, url:" + uri + ", exception:" + e.toString() + ", cost time(ms):"
+ (System.currentTimeMillis() - startTime));
} finally {
if (httpEntity != null) {
try {
EntityUtils.consumeQuietly(httpEntity);
} catch (Exception e) {
e.printStackTrace();
logger.error(
"close response exception, url:" + uri + ", exception:" + e.toString() + ", cost time(ms):"
+ (System.currentTimeMillis() - startTime));
}
}
}
return responseBody;
}
/**
* 创建请求
*
* @param uri 请求url
* @param methodName 请求的方法类型
* @param contentType contentType类型
* @param timeout 超时时间
* @return
*/
public static HttpRequestBase getRequest(String uri, String methodName, String contentType, int timeout) {
if (httpClient == null) {
initPools();
}
HttpRequestBase method = null;
if (timeout <= 0) {
timeout = DEFAUL_TTIME_OUT;
}
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout * 1000).setConnectTimeout(timeout * 1000)
.setConnectionRequestTimeout(timeout * 1000).setExpectContinueEnabled(false).build();
if (HttpPut.METHOD_NAME.equalsIgnoreCase(methodName)) {
method = new HttpPut(uri);
} else if (HttpPost.METHOD_NAME.equalsIgnoreCase(methodName)) {
method = new HttpPost(uri);
} else if (HttpGet.METHOD_NAME.equalsIgnoreCase(methodName)) {
method = new HttpGet(uri);
} else {
method = new HttpPost(uri);
}
if (StringUtils.isBlank(contentType)) {
contentType = DEFAULT_CONTENT_TYPE;
}
method.addHeader("Content-Type", contentType);
// method.addHeader("Accept", contentType);
method.addHeader("Accept", "*/*");
method.setConfig(requestConfig);
return method;
}
/**
* 执行GET 请求
*
* @param uri
* @return
*/
public static String execute(String uri) {
long startTime = System.currentTimeMillis();
HttpEntity httpEntity = null;
HttpRequestBase method = null;
String responseBody = "";
try {
if (httpClient == null) {
initPools();
}
method = getRequest(uri, HttpGet.METHOD_NAME, DEFAULT_CONTENT_TYPE, 0);
HttpContext context = HttpClientContext.create();
CloseableHttpResponse httpResponse = httpClient.execute(method, context);
httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
responseBody = EntityUtils.toString(httpEntity, "UTF-8");
logger.info("请求URL: "+uri+"+ 返回状态码:"+httpResponse.getStatusLine().getStatusCode());
}
} catch (Exception e) {
if(method != null){
method.abort();
}
e.printStackTrace();
logger.error("execute get request exception, url:" + uri + ", exception:" + e.toString() + ",cost time(ms):"
+ (System.currentTimeMillis() - startTime));
} finally {
if (httpEntity != null) {
try {
EntityUtils.consumeQuietly(httpEntity);
} catch (Exception e) {
e.printStackTrace();
logger.error("close response exception, url:" + uri + ", exception:" + e.toString() + ",cost time(ms):"
+ (System.currentTimeMillis() - startTime));
}
}
}
return responseBody;
}
}
2、请求目标的接口定义
url:http://xxx/
header/params:
paramA | 必填String,参数A,例:a |
paramB | 必填String,参数B,例:b |
paramC | 必填String,参数C,例:c |
Body:form-data
employeeNo | 必填,员工工号,如:123 |
idCard | 必填,身份证号,如:12312312312 |
返回数据,JSON结构
{
"code":200,
"msg":"success",
"data": "字符串的json"
}
3、发起请求
public class Test {
public static void main(String[] args) {
// url 请求路径
String url = "http://xxx/" + "?paramA=a¶mB=b¶mC=c";
// Body:form-data
String workNum = "123";
String idCard = "12312312312";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("employeeNo", workNum));
params.add(new BasicNameValuePair("idCard", idCard));
// 请求接口
String returnParam = HttpClientPoolUtil.executeFormData(url, params);
// 请求结果
JsonObject returnParamJo = new JsonParser().parse(returnParam).getAsJsonObject();
JsonElement codeJe = returnParamJo.get("code");
JsonElement messageJe = returnParamJo.get("msg");
JsonElement dataJe = returnParamJo.get("data");
/* 业务逻辑
.
.
.
*/
}
}