java – CloseableHttpResponse.close()和httpPost.releaseConnection()之间有什么区别?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – CloseableHttpResponse.close()和httpPost.releaseConnection()之间有什么区别?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1511字,纯文字阅读大概需要3分钟。
内容图文
![java – CloseableHttpResponse.close()和httpPost.releaseConnection()之间有什么区别?](/upload/InfoBanner/zyjiaocheng/709/99890531846b41898d778db3b223d467.jpg)
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说:
A convenience method to simplify migration from 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();
}
内容总结
以上是互联网集市为您收集整理的java – CloseableHttpResponse.close()和httpPost.releaseConnection()之间有什么区别?全部内容,希望文章能够帮你解决java – CloseableHttpResponse.close()和httpPost.releaseConnection()之间有什么区别?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。