正确使用Apache HttpClient以及何时关闭它. [英] Proper usage of Apache HttpClient and when to close it.

查看:833
本文介绍了正确使用Apache HttpClient以及何时关闭它.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Servlet中使用HttpClient来对资源进行调用,该资源在经过一些操作后作为Servlet的响应而返回.

I am using HttpClient within a servlet to make calls to a resource which I return as the servlets response after some manipulation.

我的HttpClient使用PoolingHttpClientConnectionManager.

My HttpClient uses PoolingHttpClientConnectionManager.

我这样创建客户端:

private CloseableHttpClient getConfiguredHttpClient(){
    return HttpClientBuilder
        .create()
        .setDefaultRequestConfig(config)
        .setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
        .setConnectionManagerShared(true)
        .setConnectionManager(connManager)
        .build();
}

我在servlets服务方法的尝试使用资源"中使用此客户端,因此该客户端自动关闭.要停止关闭连接管理器,请将setConnectionManagerShared设置为true.

I use this client within a Try With Resource within the servlets service method, so it is auto closed. To stop the the connection manager from being closed, I set setConnectionManagerShared to true.

我看过其他没有关闭HttpClient的代码示例.我应该关闭该资源吗?

I have seen other code samples that do not close the HttpClient. Should I not be closing this resource?

谢谢

推荐答案

有关httpcomponents的其他版本,请参见其他答案.

For other versions of httpcomponents, see other answers.

对于旧版本的httpcomponents( http://hc.apache .org/httpcomponents-client-4.2.x/quickstart.html ):

For older versions of httpcomponents (http://hc.apache.org/httpcomponents-client-4.2.x/quickstart.html):

您不需要显式关闭HttpClient,但是(您可能已经在做,但是值得注意)您应该确保在方法执行后释放连接.

You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution.

HttpClient中的ClientConnectionManager将负责维护连接状态.

The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.

 GetMethod httpget = new GetMethod("http://www.url.com/");
  try {
    httpclient.executeMethod(httpget);
    Reader reader = new InputStreamReader(httpget.getResponseBodyAsStream(), httpget.getResponseCharSet()); 
    // consume the response entity and do something awesome
  } finally {
    httpget.releaseConnection();
  } 

这篇关于正确使用Apache HttpClient以及何时关闭它.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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