CloseableHttpResponse.close()和httpPost.releaseConnection()之间有什么区别? [英] what's the difference between CloseableHttpResponse.close() and httpPost.releaseConnection()?

查看:4908
本文介绍了CloseableHttpResponse.close()和httpPost.releaseConnection()之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我做了一个http请求如上所述。

I've made a http request like above.

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

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

推荐答案

简答:

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

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.

长答案:

在任何最新版本> 4.2中可能遵循的正确模式,甚至可能在此之前,不使用 releaseConnection

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

request.releaseConnection()发布基础httpConnection,以便可以重用请求,但Java文档说:

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


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

A convenience method to simplify migration from 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();
}

这篇关于CloseableHttpResponse.close()和httpPost.releaseConnection()之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆