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(); }
- 将android连接到openLDAP服务器
- Android无效使用SingleClientConnManager:仍然分配了连接
- 如何从java servlet中的chunked响应中发送Http预告片/页脚?
- Apache DefaultHttpClient调用导致“java.lang.RuntimeException:Stub!”
- 签名小程序和服务器端控制器之间的通信
- HttpClient 4.2,基本身份validation和AuthScope
- httpclientexception“org.apache.http.conn.ConnectionPoolTimeoutException:超时等待连接”
- 使用SSL加密和NTLM身份validation的HttpClient失败
- JAVA:http发布请求