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请求。

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

简短回答:

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

答案很长:

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

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

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

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

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