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)是否正确?两次调用有什么区别?
最佳答案
简短答案:request.releaseConnection()
释放基础HTTP连接,以允许其重用。 response.close()
正在关闭一个流(不是连接),该流是我们从网络套接字流式传输的响应内容。
长答案:
在任何大于4.2的最新版本中(甚至可能在此之前)遵循的正确模式是不使用releaseConnection
。request.releaseConnection()
释放底层的httpConnection,以便可以重用该请求,但是Java文档说:
我们确保释放响应内容,而不是释放连接,从而确保释放连接并准备重用。一个简短的示例如下所示:
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();
}