1
看着它给出了下面的代码示例quick start guide:为什么Apache CloseableHttpResponse不能关闭实体?
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager.
try {
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity1);
} finally {
response1.close();
}
在上面的代码中的两点意见说,我们必须关闭响应对象
“系统资源的正确释放”
和
“,如果响应内容未被完全消耗,则底层连接无法安全地重新使用,并且将被连接管理器关闭并丢弃。
现在Apache已经非常好地为我们实现了CloseableHttpResponse,这意味着我们可以使用try-with-resources块。但close方法只关闭响应对象,为什么它不消耗实体?