一、HttpClient 4.X建议使用CloseableHttpClient 及CloseableHttpResponse 。
CloseableHttpClient client = HttpClients.createDefault();--默认是使用连接池:PollingHttpClientConnectionManager,并默认对每个Route,HttpClient仅维护2个连接,总数不超过20个连接。
CloseableHttpResponse response = client.execute(request);
另外如果
HttpEntity entity = response.getEntity();
InputStream is=entity.getContent();
可以使用is.close();将底层流关闭,也可以使用EntityUtils.consume(entity)把流给关闭。
例:
对于实体的资源使用完之后要适当的回收资源,特别是对于流实体:例子代码如下
public static void test() throws IllegalStateException, IOException{
HttpResponseresponse=null;
HttpEntityentity=response.getEntity();
if(entity!=null){
InputStreamis=entity.getContent();
try{
//做一些操作
}finally{
//最后别忘了关闭应该关闭的资源,适当的释放资源
if(is != null){
is.close();//此处也可以EntityUtils.consume(entity);
}
二、关闭Httpclient的流程
1、当使用了自己配置的Http连接池后,可以如下关闭
CloseableHttpClient client = 自定义的获取client客户端的方法;//注意此client做成单例
CloseableHttpResponse response = null;
// 发送get请求
HttpGet request = null;
try{
request = new HttpGet(url);
response = client.execute(request);
//业务代码
}catch (Exception e){
log.error("get请求提交失败:" + url, e);
}
finally{
if(null != response ){
try {
response .close();//此处就只关闭Response等底层流,而httpclient不用关闭,保持socket放入缓存池中
} catch (IOException e) {
log.error("关闭失败:" , e);
}
}
}
参考:https://blog.csdn.net/a363722188/article/details/82425412
2、每一次请求生成一个httpclient
finally {
if (null != response) {
try {
response.close();
}catch (IOException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
}
if (null != client){
try {
client.close();
}catch (IOException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
}
}
参考:https://www.jianshu.com/p/83bbeb33ed20