2017-04-17 522 views
3

我在一个servlet中使用HttpClient来调用一个资源,我经过一些操作后返回servlet响应。正确使用Apache HttpClient以及何时关闭它。

我的HttpClient使用PoolingHttpClientConnectionManager。

创建客户端,像这样:

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

我用servlet的服务方法中的尝试资源中此客户端,所以它是自动关闭。要停止关闭连接管理器,我将setConnectionManagerShared设置为true。

我看过其他不关闭HttpClient的代码示例。我应该不是关闭这个资源吗?

感谢

回答

1

你不定义明确地关闭HttpClient的,但是,(你可能已经在做,但是值得一提的),你应该保证连接方法执行后释放。

编辑:HttpClient中的ClientConnectionManager将负责维护连接状态。

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

我发现你真的需要关闭资源如文档中:https://hc.apache.org/httpcomponents-client-ga/quickstart.html

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(); 
    EntityUtils.consume(entity1); 
} finally { 
    response1.close(); 
} 
相关问题