java - 为什么 Apache CloseableHttpResponse 在关闭时不使用实体?

标签 java apache apache-httpclient-4.x autocloseable

看着quick start guide它给出了以下代码示例:

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();
}

上面代码中的两条注释说我们必须关闭响应对象

"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方法只是关闭了响应对象,为什么不也消费实体呢?

最佳答案

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

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

代码片段将确保正确解除资源分配,同时尝试保持底层连接处于 Activity 状态。

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());
} 

关于java - 为什么 Apache CloseableHttpResponse 在关闭时不使用实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469833/

相关文章:

java - Android - 从警报生成器对话框检索文本输入

java - 如何使用 JDBC 创建 MySql 数据库

java - DefaultHttpClient 单例实例的超时

php - 获取错误无法加载资源 : the server responded with a status of 413 (Request Entity Too Large) on ajax upload

java - 带有 mod_jk 的 Apache/Tomcat 中的多个子域

java - PoolingHttpClientConnectionManager 不释放连接

java - 如果我不使用自定义连接管理器,是否仍应在 Apache HttpClient 上设置 ConnectionRequestTimeout?

java - Android 如何响应主页点击

java - 在 Java 中,如何将一个 64 位的字符串分成四个 16 位的字符串?

php - 如何限制PHP文件访问执行目录?