为什么Apache CloseableHttpResponse在关闭时不使用该实体? [英] Why does Apache CloseableHttpResponse not consume the entity on close?
问题描述
查看快速入门指南提供了以下代码示例:
Looking at the quick start guide it gives the following code example:
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();
}
上面的代码中的两个注释表明我们必须关闭
The two comments in the code above say that we must close the response object for
正确释放系统资源"
"correct deallocation of system resources"
和
如果未完全使用响应内容,则无法安全地重用基础连接,连接管理器将关闭并丢弃该连接."
"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".
现在,Apache非常友好地为我们实现了CloseableHttpResponse,这意味着我们可以使用try-with-resources块.但是close方法仅关闭响应对象,为什么它还不消耗实体?
Now Apache have very kindly implementend a CloseableHttpResponse for us, which means we can use a try-with-resources block. But the close method only closes the response object, why doesn't it also consume the entity?
推荐答案
因为此时很难说调用者是否打算重用基础连接.在某些情况下,您可能只想从较大的响应主体中读取一小块,然后立即终止连接.
Because it is hard to say at that point whether or not the caller intends to re-use the underlying connection. In some cases one may want to read just a small chunk from a large response body and immediately terminate the connection.
换句话说,同一件事一遍又一遍地发生:没有一种方法可以使每个人都开心.
In other words, the same thing happens over and over again: there is no one way that can make everyone happy.
该代码段将确保在适当地释放资源的同时尝试使基础连接保持活动状态.
The code snippet will do ensure proper de-allocation of resources while trying to keep the underlying connection alive.
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());
}
这篇关于为什么Apache CloseableHttpResponse在关闭时不使用该实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!