2017-06-10 28 views
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方法只关闭响应对象,为什么它不消耗实体?

回答

0

因为目前很难说主叫方是否打算重新使用底层连接。在某些情况下,人们可能只想从大型响应主体中读取一小块,并立即终止连接。

换句话说,同样的事情会一遍又一遍地发生:没有一种方法可以让每个人都开心。

该代码片段将确保在尝试保持底层连接处于活动状态时正确解除资源分配。

CloseableHttpClient httpclient = HttpClients.createDefault(); 
HttpGet httpGet = new HttpGet("http://targethost/homepage"); 
CloseableHttpResponse response1 = httpclient.execute(httpGet); 
try { 
    System.out.println(response1.getStatusLine()); 
} finally { 
    EntityUtils.consume(response1.getEntity()); 
}