Apache HttpClient Response Hadling in Java


Apache HttpClient library provides the ResponseHandler interface. By implementing ResponseHandler you can handle HTTP responses in a clean way. Using the response handler is the recommended way of executing HTTP requests and processing HTTP responses. This approach of handling response enables the caller to concentrate on the process of digesting HTTP responses and to delegate the task of system resource deallocation to HttpClient. The use of an HTTP response handler guarantees that the underlying HTTP connection will be released back to the connection manager automatically in all cases.

Use the following Gradle dependency:

// https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.7'

Example of Apache HttpClient Response Handling:

public class HttpClienResponseHandler {

	public final static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("https://www.google.co.in/");

            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler responseHandler = new ResponseHandler() {

                @Override
                public String handleResponse(
                        final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity) : null;
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
        } finally {
            httpclient.close();
        }
    }
}

Using the above approach you can handle REST response to deserialize objects in designated type.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.