【发布时间】:2019-11-21 21:31:14
【问题描述】:
这是一个示例程序。
public class Foobar {
private HttpClient;
public Foobar(RequestConfig config, PoolingHttpClientConnectionManager, connManager) {
return HttpClients.custom()
.setDefaultRequestConfig(config)
.setConnectionManager(connManager)
.build();
}
public Foobarrr execute() {
HttpPost httpPost = new HttpPost("/blah");
HttpResponse response;
try {
response = httpClient.execute(httpPost);
else if (response.getEntity().getContent() != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
return mapper.readValue(response.getEntity().getContent(), Foobarrr.class);
}
catch(Exception ex){
throw new RuntimeException(ex);
}
在上述情况下,客户端只创建一次,但可以重复使用。 我在互联网上看到另一个版本的代码,其中 httpClient 在 try-catch 中关闭。这不是一件昂贵的事情吗,或者与上述方式相比,这有什么优势
public void executeWithPooledUsingHttpClientBuilder() throws Exception {
try (CloseableHttpClient httpClient = HttpClients.custom()
.setMaxConnTotal(100)
.setMaxConnPerRoute(20)
.build()) {
final HttpGet httpGet = new HttpGet(GET_URL);
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
EntityUtils.consumeQuietly(response.getEntity());
}
}
【问题讨论】:
标签: java httpurlconnection connection-pooling apache-httpclient-4.x