我在一个 servlet 中使用 HttpClient 来调用一个资源,我在一些操作后将其作为 servlet 响应返回。
我的 HttpClient 使用 PoolingHttpClientConnectionManager。
我这样创建客户端:
private CloseableHttpClient getConfiguredHttpClient(){
return HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
.setConnectionManagerShared(true)
.setConnectionManager(connManager)
.build();
}
我在 servlet 服务方法中的 Try With Resource 中使用此客户端,因此它会自动关闭。为了阻止连接管理器被关闭,我将 setConnectionManagerShared
设置为 true。
我见过其他不关闭 HttpClient 的代码示例。我不应该关闭这个资源吗?
谢谢
最佳答案
对于 httpcomponents 版本 4.5.x:
我发现您确实需要关闭资源,如文档所示:https://hc.apache.org/httpcomponents-client-4.5.x/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();
}
关于java - 正确使用 Apache HttpClient 以及何时关闭它。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43454514/