Here is a sample program.
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);
}
In the above case, the client is created only once but reused. I see another version of code in the internet where the httpClient is closed in try-catch. Isn't that an expensive thing or what is the advantage of this over the above way of doing
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());
}
}