Apache HttpClient Interceptor
October 25, 2018
On this page we will provide Apache HttpClient interceptor example. Apache HttpClient adds HttpRequestInterceptor
and HttpResponseInterceptor
protocol interceptors to CloseableHttpClient
using HttpClientBuilder
class. HttpClientBuilder
is used to build CloseableHttpClient
custom configurations. To add interceptor, HttpClientBuilder
provides methods such as addRequestInterceptorFirst
, addResponseInterceptorLast
, addExecInterceptorAfter
, addExecInterceptorBefore
etc. Here in our example we will add request id in header and according to that value we will change entity details.
Contents
Technologies Used
Find the technologies being used in our example.1. Java 9
2. HttpClient5 5.0-beta1
3. Gradle 4.3.1
4. Eclipse Oxygen
Gradle File
Find the Gradle file used in the example.build.gradle
apply plugin: 'java' apply plugin: 'eclipse' archivesBaseName = 'concretepage' repositories { mavenCentral() } dependencies { compile 'org.apache.httpcomponents.client5:httpclient5:5.0-beta1' compile 'org.apache.httpcomponents.client5:httpclient5-fluent:5.0-beta1' }
HttpRequestInterceptor and HttpResponseInterceptor
HttpRequestInterceptor
and HttpResponseInterceptor
protocol interceptors act upon one header or the group of related headers of the incoming messages or they can populate the one header or group of related headers of the outgoing messages. HttpRequestInterceptor
and HttpResponseInterceptor
are interfaces and both declare process
method.
Find the code snippet to instantiate
HttpRequestInterceptor
.
new HttpRequestInterceptor() { @Override public void process(HttpRequest request, EntityDetails entity, HttpContext context) throws HttpException, IOException { ------ } }
HttpResponseInterceptor
.
new HttpResponseInterceptor() { @Override public void process(HttpResponse response, EntityDetails entity, HttpContext context) throws HttpException, IOException { ------ } }
ExecChainHandler
ExecChainHandler
is an element in HTTP request execution chain. ExecChainHandler
is an interface and declares execute
method. We can instantiate ExecChainHandler
as following.
new ExecChainHandler() { @Override public ClassicHttpResponse execute(ClassicHttpRequest request, Scope scope, ExecChain chain) throws IOException, HttpException { ------ } }
Add Interceptors using HttpClientBuilder
HttpClientBuilder
provides following methods to add interceptors.
addRequestInterceptorFirst: Adds the protocol interceptor to the head of the protocol processing list. It can accept
HttpRequestInterceptor
or HttpResponseInterceptor
interceptor as an argument.
addResponseInterceptorLast: Adds the protocol interceptor to the tail of the protocol processing list. It can accept
HttpRequestInterceptor
or HttpResponseInterceptor
interceptor as an argument.
addExecInterceptorAfter: It adds execution interceptor after the given interceptor. This method accepts (1) existing interceptor name after which this execution interceptor will be added, (2) name for this interceptor and (3)
ExecChainHandler
instance.
addExecInterceptorBefore: It adds execution interceptor before the given interceptor. This method accepts (1) existing interceptor name before which this execution interceptor will be added, (2) name for this interceptor and (3)
ExecChainHandler
instance.
addExecInterceptorFirst: Adds execution interceptor to the head of the processing list. It accepts interceptor name and
ExecChainHandler
instance.
addExecInterceptorLast: Adds execution interceptor to the tail of the processing list. It accepts interceptor name and
ExecChainHandler
instance.
Find the example.
MyClientInterceptors.java
package com.concretepage; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import org.apache.hc.client5.http.classic.ExecChain; import org.apache.hc.client5.http.classic.ExecChain.Scope; import org.apache.hc.client5.http.classic.ExecChainHandler; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.ChainElements; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.EntityDetails; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpRequest; import org.apache.hc.core5.http.HttpRequestInterceptor; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.HttpResponseInterceptor; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.ParseException; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.message.BasicClassicHttpResponse; import org.apache.hc.core5.http.protocol.HttpContext; public class MyClientInterceptors { public static void main(String[] args) throws IOException, ParseException { HttpClientBuilder builder = HttpClients.custom(); // Add HttpRequestInterceptor builder.addResponseInterceptorLast(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, EntityDetails entity, HttpContext context) throws HttpException, IOException { System.out.println("addResponseInterceptorLast with HttpRequestInterceptor"); context.setAttribute("name", "Mahesh"); } }); builder.addRequestInterceptorFirst(new HttpRequestInterceptor() { private final AtomicLong count = new AtomicLong(0); @Override public void process(final HttpRequest request, final EntityDetails entity, final HttpContext context) throws HttpException, IOException { System.out.println("addRequestInterceptorFirst with HttpRequestInterceptor"); request.setHeader("requestId", Long.toString(count.incrementAndGet())); System.out.println(context.getAttribute("name")); } }); // Execution Interceptors builder.addExecInterceptorAfter(ChainElements.PROTOCOL.name(), "AAA", new ExecChainHandler() { @Override public ClassicHttpResponse execute(ClassicHttpRequest request, Scope scope, ExecChain chain) throws IOException, HttpException { System.out.println("--Execution Interceptor AAA--"); Header header = request.getFirstHeader("requestId"); if (header != null && "2".equalsIgnoreCase(header.getValue())) { ClassicHttpResponse response = new BasicClassicHttpResponse(HttpStatus.SC_NOT_FOUND, "Not Found"); response.setEntity(new StringEntity("Data not available", ContentType.TEXT_PLAIN)); return response; } else { return chain.proceed(request, scope); } } }); builder.addExecInterceptorBefore("AAA", "BBB", new ExecChainHandler() { @Override public ClassicHttpResponse execute(ClassicHttpRequest request, Scope scope, ExecChain chain) throws IOException, HttpException { System.out.println("--Execution Interceptor before AAA--"); return chain.proceed(request, scope); } }); builder.addExecInterceptorAfter("AAA", "CCC", new ExecChainHandler() { @Override public ClassicHttpResponse execute(ClassicHttpRequest request, Scope scope, ExecChain chain) throws IOException, HttpException { System.out.println("--Execution Interceptor after AAA--"); return chain.proceed(request, scope); } }); // Add HttpResponseInterceptor builder.addResponseInterceptorLast(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, EntityDetails entity, HttpContext context) throws HttpException, IOException { System.out.println("addResponseInterceptorLast with HttpResponseInterceptor"); System.out.println(context.getAttribute("name")); } }); builder.addRequestInterceptorFirst(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, EntityDetails entity, HttpContext context) throws HttpException, IOException { System.out.println("addRequestInterceptorFirst with HttpResponseInterceptor"); System.out.println(context.getAttribute("name")); } }); for (int i = 1; i <= 2; i++) { System.out.println("-----------Request " + i + "-------------"); try (CloseableHttpClient httpClient = builder.build()) { final HttpGet httpGet = new HttpGet("http://httpbin.org/get"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { System.out.println("-------Output---------"); System.out.println(response.getCode() + " " + response.getReasonPhrase()); System.out.println(EntityUtils.toString(response.getEntity())); } } } } }
Output
-----------Request 1------------- addResponseInterceptorLast with HttpRequestInterceptor addRequestInterceptorFirst with HttpRequestInterceptor Mahesh --Execution Interceptor before AAA-- --Execution Interceptor AAA-- --Execution Interceptor after AAA-- addResponseInterceptorLast with HttpResponseInterceptor Mahesh addRequestInterceptorFirst with HttpResponseInterceptor Mahesh -------Output--------- 200 OK { "args": {}, "headers": { "Accept-Encoding": "deflate, gzip, x-gzip", "Connection": "close", "Host": "httpbin.org", "Requestid": "1", "User-Agent": "Apache-HttpClient/5.0-beta1 (Java/9)" }, "origin": "157.38.199.122", "url": "http://httpbin.org/get" } -----------Request 2------------- addResponseInterceptorLast with HttpRequestInterceptor addRequestInterceptorFirst with HttpRequestInterceptor Mahesh --Execution Interceptor before AAA-- --Execution Interceptor AAA-- addResponseInterceptorLast with HttpResponseInterceptor Mahesh addRequestInterceptorFirst with HttpResponseInterceptor Mahesh -------Output--------- 404 Not Found Data not available
References
HttpComponents HttpClient OverviewHttpClientBuilder
HttpRequestInterceptor
HttpResponseInterceptor