gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:52:45 26 4
gpt4 key购买 nike

看着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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com