Apache HttpClient Response Handler
October 13, 2018
On this page we will provide Apache HttpClient Response Handler example. Apache HttpClient provides HttpClientResponseHandler
to process responses. It enables the caller to concentrate on digesting HTTP responses and delegating the task. HTTP response handler ensures that HTTP connection will be released to connection manger automatically in all cases. Apache provides BasicHttpClientResponseHandler
and ContentResponseHandler
as the implementations of HttpClientResponseHandler
interface. We can also create custom response handler by implementing HttpClientResponseHandler
and overriding its handleResponse
method.
Contents
Technologies Used
Find the technologies being used in our example.1. Java 9
2. HttpClient5 5.0-beta1
3. Jackson 2.9.4
4. Gradle 4.3.1
5. Eclipse Oxygen
Gradle File
Find the Gradle file used in the example.build.gradle
apply plugin: 'java' apply plugin: 'eclipse' archivesBaseName = 'concretepage' version = '1' repositories { mavenCentral() } dependencies { compile 'org.apache.httpcomponents.client5:httpclient5:5.0-beta1' compile 'org.apache.httpcomponents.client5:httpclient5-fluent:5.0-beta1' compile 'com.fasterxml.jackson.core:jackson-core:2.9.5' compile 'com.fasterxml.jackson.core:jackson-databind:2.9.5' compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.5' }
HttpClientResponseHandler
HttpClientResponseHandler
handles the process of generating response object from ClassicHttpResponse
which encloses HttpEntity
. HttpEntity
is an auto closable entity that can be sent or received with HTTP message. Apache provides following implementations of
HttpClientResponseHandler
.
BasicHttpClientResponseHandler: It returns the response body as string for successful responses.
ContentResponseHandler: It converts response as
Content
instances.
HttpClientResponseHandler
is an interface and declares handleResponse
method. To create a custom HttpClient response handler, we need to implement HttpClientResponseHandler
and override its handleResponse
method.
BasicHttpClientResponseHandler for String
BasicHttpClientResponseHandler
returns the response body as string for successful responses. If response code is 300 or greater, exception is thrown. Find the example.
BasicHCRespHandlerDemo.java
package com.concretepage; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.BasicHttpClientResponseHandler; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.io.HttpClientResponseHandler; public class BasicHCRespHandlerDemo { public final static void main(final String[] args) throws Exception { final CloseableHttpClient httpClient = HttpClients.createDefault(); try (httpClient) { final HttpGet httpGet = new HttpGet("http://httpbin.org/get"); HttpClientResponseHandler<String> responseHandler = new BasicHttpClientResponseHandler(); final String responseBody = httpClient.execute(httpGet, responseHandler); System.out.println(responseBody); } } }
ContentResponseHandler for Content
ContentResponseHandler
converts response as Content
instances. Find the example.
package com.concretepage; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.fluent.Content; import org.apache.hc.client5.http.fluent.ContentResponseHandler; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.io.HttpClientResponseHandler; public class ContentRespHandlerDemo { public final static void main(final String[] args) throws Exception { final CloseableHttpClient httpClient = HttpClients.createDefault(); try (httpClient) { final HttpGet httpGet = new HttpGet("http://httpbin.org/get"); HttpClientResponseHandler<Content> responseHandler = new ContentResponseHandler(); final Content content = httpClient.execute(httpGet, responseHandler); System.out.println(content.asString()); } } }
Custom Response Handler for JSON
Here we will create custom response handler by implementingHttpClientResponseHandler
and overriding its handleResponse
method. For the demo we are using a sample URL that will return JSON response as following.
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
handleResponse
method, we will deserialize JSON data into User
object using Jackson API. Find the example.
CustomResponseHandler.java
package com.concretepage; import java.io.IOException; import java.io.InputStream; import org.apache.hc.client5.http.ClientProtocolException; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.io.HttpClientResponseHandler; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.ObjectMapper; public class CustomResponseHandler implements HttpClientResponseHandler<User> { @Override public User handleResponse(ClassicHttpResponse response) throws HttpException, IOException { final int status = response.getCode(); if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) { final JsonFactory jsonFactory = new JsonFactory(); try (HttpEntity httpEntity = response.getEntity(); InputStream inputStream = httpEntity.getContent()) { JsonParser jsonParser = jsonFactory.createParser(inputStream); jsonParser.setCodec(new ObjectMapper()); User user = jsonParser.readValueAs(User.class); return user; } } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }
package com.concretepage; public class User { private String id; private String userId; private String title; private Boolean completed; public String getId() { return id; } public String getUserId() { return userId; } public String getTitle() { return title; } public Boolean getCompleted() { return completed; } }
package com.concretepage; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.io.HttpClientResponseHandler; public class ClientWithCustomRespHandler { public final static void main(final String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); try (httpClient) { final HttpGet httpGet = new HttpGet("https://jsonplaceholder.typicode.com/todos/1"); HttpClientResponseHandler <User> responseHandler = new CustomResponseHandler(); final User user = httpClient.execute(httpGet, responseHandler); System.out.println("UserId: " + user.getUserId()); System.out.println("Title: " + user.getTitle()); } } }
UserId: 1 Title: delectus aut autem
References
HttpComponents HttpClient OverviewInterface HttpClientResponseHandler