1. Overview

In this tutorial, we’ll look at how we can use the ResponseHandler interface to consume the Apache HttpClient responses. The ResponseHandler interface provides us a better way to consume a response and release the associated system resources.

2. ResponseHandler Usage

Let’s first look at the traditional approach.

In the traditional approach, we get the response, apply some business logic and then release the system resources:

public void handleStatusCodes() throws Exception {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final HttpGet httpGet = new HttpGet(GET_URL);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                EntityUtils.consumeQuietly(response.getEntity());
            }
            String responseBody = EntityUtils.toString(response.getEntity());
        }
    }
}

Here, we’re getting the response and consuming the response even if the status is OK or not. This is important because we should consume the response to release the system resources.

The advantage of using ResponseHandler is that resource management is handled by the HttpClient. As a result, it enables us to implement the required functionality with fewer pitfalls.

Let’s see how we can use a ResponseHandler implementation:

public void executeGet() throws Exception {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        final HttpGet httpGet = new HttpGet(GET_URL);
        String responseBody = httpClient.execute(httpGet, new ResponseHandler<String>() {
            @Override
            public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
                StatusLine statusLine = httpResponse.getStatusLine();
                if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
                    return null;
                }
                return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
            }
        });
    }
}

Here, we have a similar logic with the previous example. However, in this case, we’re encapsulating the response processing in a ResponseHandler implementation and HttpClient is executing it. Furthermore, even if we don’t consume the response entity when the status isn’t OK, HttpClient does it for us.

3. Summary

In this tutorial, we’ve investigated the ResponseHandler interface of Apache HttpClient.

As always, the source code is available on Github.

Leave a Reply

Close Menu