实现项目中的HttpUtil用到CloseableHttpClient,httpUtil源码:https://download.csdn.net/download/imwucx/88378340
于是学习CloseableHttpClient并记录一下。
CloseableHttpClient实现了AutoCloseable接口和HttpClient接口,可以自动关闭连接管理器和销毁HttpClient实例。不仅可以简单设置请求头,还可以利用fastjson转换请求或返回结果字符串为json格式。
1、创建CloseableHttpClient实例
HttpClients.createDefault()
2、创建请求实例
HttpPost post = new HttpPost(url);
3、设置请求参数
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
4、执行请求
HttpResponse res = httpClient.execute(post);
5、处理返回结果
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
respJson = JSONObject.parseObject(result);
}
6、连接池
使用连接池来提高性能
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", createSSLConnSocketFactory())
.build();
// 设置连接池
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 设置连接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connMgr).build();
7、关闭连接池
httpClient.close();
在应用程序结束时,应关闭连接管理器以释放所有的系统资源。
Registry socketFactoryRegistry = RegistryBuilder.create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", createSSLConnSocketFactory())
.build();
// 设置连接池
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 设置连接池大小
connMgr.setMaxTotal(100);
connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
RequestConfig.Builder configBuilder = RequestConfig.custom();
// 设置连接超时
configBuilder.setConnectTimeout(MAX_TIMEOUT);
// 设置读取超时
configBuilder.setSocketTimeout(MAX_TIMEOUT);
// 设置从连接池获取连接实例的超时
configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
// 在提交请求之前 测试连接是否可用
configBuilder.setStaleConnectionCheckEnabled(true);
requestConfig = configBuilder.build();
CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
HttpGet httpGet = new HttpGet("http://www.example.com");
httpGet.setConfig(config);
CloseableHttpClient httpClient = HttpClients.createDefault();
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
设置异常重试
CloseableHttpClient httpClient = HttpClients.custom()
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true))
.build();