/**
*创建httpClient
*/
public HttpClient createHttpClient() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager =
new PoolingHttpClientConnectionManager();
return httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager).
setMaxConnPerRoute(20).
setMaxConnTotal(20).
evictExpiredConnections().
evictIdleConnections(5000, TimeUnit.MILLISECONDS).
setRetryHandler(new StandardHttpRequestRetryHandler()).
setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy()).
build();
}
/**
* 通过httpClient 发送get请求
* 在创建httpClient时 evictExpiredConnections 为true,调用完成会自动关闭
* @param url url
* @param map 参数
* @param params 需要转码的key 数组
* @return org.apache.http.HttpEntity
*/
public HttpEntity sendGet(String url, Map<String, String> map, String... params) {
StringBuilder builder = new StringBuilder(url);
builder.append("?");
HttpClient httpClient = null;
try {
if (params.length > 0) {
for (String param : params) {
map.replace(param, URLEncoder.encode(map.get(param), "UTF-8"));
}
}
map.forEach((key, value) -> builder.append(key).append("=").append(value).append("&"));
String uri = builder.deleteCharAt(builder.lastIndexOf("&")).toString();
httpClient = httpClientConfig.createHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse execute = httpClient.execute(get);
return execute.getEntity();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}