CloseableHttpResponse response = null;
try {
// do some thing ....
HttpPost request = new HttpPost("some url");
response = getHttpClient().execute(request);
// do some other thing ....
} catch(Exception e) {
// deal with exception
} finally {
if(response != null) {
try {
response.close(); // (1)
} catch(Exception e) {}
request.releaseConnection(); // (2)
}
}
我已经提出了如上所述的http请求。
为了释放底层连接,调用(1)和(2)是否正确?以及两次调用之间的区别是什么?
答案 0 :(得分:17)
简短回答:
request.releaseConnection()
正在释放底层HTTP连接以允许它被重用。 response.close()
正在关闭流(不是连接),此流是我们从网络套接字流式传输的响应内容。
长答案:
在任何最新版本中遵循的正确模式> 4.2甚至可能在此之前,不使用releaseConnection
。
request.releaseConnection()
释放底层的httpConnection,以便可以重用请求,但是Java文档说:
简化从HttpClient 3.1 API迁移的便捷方法......
我们确保响应内容被完全消耗,而不是释放连接,这反过来确保连接被释放并准备好重用。一个简短的例子如下所示:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
String bodyAsString = EntityUtils.toString(exportResponse.getEntity());
System.out.println(bodyAsString);
// and ensure it is fully consumed (this is how stream is released.
EntityUtils.consume(entity1);
} finally {
response1.close();
}