Java CloseableHttpResponse.close() 和 httpPost.releaseConnection() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30889984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:19:45  来源:igfitidea点击:

What's the difference between CloseableHttpResponse.close() and httpPost.releaseConnection()?

javahttpclient

提问by wyang

CloseableHttpResponse response = null;
try {
    // do some thing ....
    HttpPost request = new HttpPost("some url");
    response = getHttpClient().execute(request);
    // do some other thing ....
} catch(Exception e) {
    // deal with exception
} finally {
    if(response != null) {
        try {
            response.close(); // (1)
        } catch(Exception e) {}
        request.releaseConnection(); // (2)
    }
}

I've made a http request like above.

我已经提出了一个像上面这样的 http 请求。

In order to release the underlying connection, is it correct to call (1) and (2)? and what's the difference between the two invocation?

为了释放底层连接,调用(1)和(2)是否正确?这两个调用之间有什么区别?

回答by Matt

Short answer:

简短的回答:

request.releaseConnection()is releasing the underlying HTTP connection to allow it to be reused. response.close()is closing a stream (not a connection), this stream is the response content we are streaming from the network socket.

request.releaseConnection()正在释放底层 HTTP 连接以允许它被重用。response.close()正在关闭一个流(不是连接),这个流是我们从网络套接字流式传输的响应内容。

Long Answer:

长答案:

The correct pattern to follow in any recent version > 4.2 and probably even before that, is not to use releaseConnection.

在任何最新版本 > 4.2 甚至可能更早版本中遵循的正确模式是不要使用releaseConnection.

request.releaseConnection()releases the underlying httpConnection so the request can be reused, however the Java doc says:

request.releaseConnection()释放底层 httpConnection 以便可以重用请求,但是 Java 文档说:

A convenience method to simplify migration from HttpClient 3.1 API...

一种简化从 HttpClient 3.1 API 迁移的便捷方法...

Instead of releasing the connection, we ensure the response content is fully consumed which in turn ensures the connection is released and ready for reuse. A short example is shown below:

我们不会释放连接,而是确保响应内容被完全消耗,从而确保连接被释放并准备好重用。一个简短的例子如下所示:

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://targethost/homepage");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
    System.out.println(response1.getStatusLine());
    HttpEntity entity1 = response1.getEntity();
    // do something useful with the response body
    String bodyAsString = EntityUtils.toString(exportResponse.getEntity());
    System.out.println(bodyAsString);
    // and ensure it is fully consumed (this is how stream is released.
    EntityUtils.consume(entity1);
} finally {
    response1.close();
}