Hal*_*lex 8 java servlets httpclient
我在servlet中使用HttpClient来调用一些资源,我在一些操作之后作为servlets响应返回.
我的HttpClient使用PoolingHttpClientConnectionManager.
我像这样创建客户端:
private CloseableHttpClient getConfiguredHttpClient(){
return HttpClientBuilder
.create()
.setDefaultRequestConfig(config)
.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
.setConnectionManagerShared(true)
.setConnectionManager(connManager)
.build();
}
Run Code Online (Sandbox Code Playgroud)
我在servlets服务方法中的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();
}
Run Code Online (Sandbox Code Playgroud)
您无需显式关闭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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11398 次 |
| 最近记录: |