Interceptors are those which helps to obstruct or change requests or responses. Protocol interceptors in general act upon a specific header or a group of related headers. HttpClient library provides support for interceptors.

Request interceptor

The HttpRequestInterceptor interface represents the request interceptors. This interface contains a method known as a process in which you need to write the chunk of code to intercept the requests.

On the client side, this method verifies/processes the requests before sending them to the server and, on the server side, this method is executed before evaluating the body of the request.

Creating request interceptor

You can create a request interceptor by following the steps given below.

Step 1 - Create an object of HttpRequestInterceptor

Create an object of the HttpRequestInterceptor interface by implementing its abstract method process.

  1. HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {

  1. @Override
  2. public void process(HttpRequest request, HttpContext context) throws
  3. HttpException, IOException {
  4. //Method implementation . . . . .
  5. };

Step 2 - Instantiate CloseableHttpClient object

Build a custom CloseableHttpClient object by adding above created interceptor to it as shown below −

  1. //Creating a CloseableHttpClient object
  2. CloseableHttpClient httpclient =
  3. HttpClients.custom().addInterceptorFirst(requestInterceptor).build();

Using this object, you can carry out the request executions as usual.

Example

Following example demonstrates the usage of request interceptors. In this example, we have created a HTTP GET request object and added three headers: sample-header, demoheader, and test-header to it.

In the processor() method of the interceptor, we are verifying the headers of the request sent; if any of those headers is sample-header, we are trying to remove it and display the list of headers of that particular request.

  1. import java.io.IOException;
  2. import org.apache.http.Header;
  3. import org.apache.http.HttpException;
  4. import org.apache.http.HttpRequest;
  5. import org.apache.http.HttpRequestInterceptor;
  6. import org.apache.http.HttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.impl.client.CloseableHttpClient;
  9. import org.apache.http.impl.client.HttpClients;
  10. import org.apache.http.message.BasicHeader;
  11. import org.apache.http.protocol.HttpContext;
  12.  
  13. public class InterceptorsExample {
  14.  
  15. public static void main(String args[]) throws Exception{
  16.  
  17. //Creating an HttpRequestInterceptor
  18. HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
  19. @Override
  20. public void process(HttpRequest request, HttpContext context) throws
  21. HttpException, IOException {
  22. if(request.containsHeader(“sample-header”)) {
  23. System.out.println(“Contains header sample-header, removing it..”);
  24. request.removeHeaders(“sample-header”);
  25. }
  26. //Printing remaining list of headers
  27. Header[] headers= request.getAllHeaders();
  28. for (int i = 0; i<headers.length;i++) {
  29. System.out.println(headers[i].getName());
  30. }
  31. }
  32. };
  33.  
  34. //Creating a CloseableHttpClient object
  35. CloseableHttpClient httpclient =
  36. HttpClients.custom().addInterceptorFirst(requestInterceptor).build();
  37.  
  38. //Creating a request object
  39. HttpGet httpget1 = new HttpGet(“https://www.tutorialspoint.com/“);
  40.  
  41. //Setting the header to it
  42. httpget1.setHeader(new BasicHeader(“sample-header”,”My first header”));
  43. httpget1.setHeader(new BasicHeader(“demo-header”,”My second header”));
  44. httpget1.setHeader(new BasicHeader(“test-header”,”My third header”));
  45.  
  46. //Executing the request
  47. HttpResponse httpresponse = httpclient.execute(httpget1);
  48.  
  49. //Printing the status line
  50. System.out.println(httpresponse.getStatusLine());
  51. }
  52. }
### Output

On executing the above program, the following output is generated −

  1. Contains header sample-header, removing it..
  2. demo-header
  3. test-header
  4. HTTP/1.1 200 OK
## Response interceptor

The HttpResponseInterceptor interface represents the response interceptors. This interface contains a method known as process(). In this method, you need to write the chunk of code to intercept the responses.

On the server side, this method verifies/processes the response before sending them to the client, and on the client side, this method is executed before evaluating the body of the response.

Creating response interceptor

You can create a response interceptor by following the steps given below −

Step 1 - Create an object of HttpResponseInterceptor

Create an object of the HttpResponseInterceptor interface by implementing its abstract method process.

  1. HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
  2. @Override
  3. public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
  4. //Method implementation . . . . . . . .
  5. }
  6. };
### Step 2: Instantiate CloseableHttpClient object

Build a custom CloseableHttpClient object by adding above created interceptor to it, as shown below −

  1. //Creating a CloseableHttpClient object
  2. CloseableHttpClient httpclient =
  3. HttpClients.custom().addInterceptorFirst(responseInterceptor).build();

Using this object, you can carry out the request executions as usual.

Example

The following example demonstrates the usage of response interceptors. In this example, we have added three headers: sample-header, demo-header, and test-header to the response in the processor.

After executing the request and obtaining the response, we printed names of all the headers of the response using the getAllHeaders() method.

And in the output, you can observe the names of three headers in the list.

  1. import java.io.IOException;
  2. import org.apache.http.Header;
  3. import org.apache.http.HttpException;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.HttpResponseInterceptor;
  6. import org.apache.http.client.methods.HttpGet;
  7. import org.apache.http.impl.client.CloseableHttpClient;
  8. import org.apache.http.impl.client.HttpClients;
  9. import org.apache.http.protocol.HttpContext;
  10.  
  11. public class ResponseInterceptorsExample {
  12.  
  13. public static void main(String args[]) throws Exception{
  14.  
  15. //Creating an HttpRequestInterceptor
  16. HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
  17. @Override
  18. public void process(HttpResponse response, HttpContext context) throws
  19. HttpException, IOException {
  20. System.out.println("Adding header sample_header, demo-header, test_header to the response");
  21. response.setHeader("sample-header", "My first header");
  22. response.setHeader("demo-header", "My second header");
  23. response.setHeader("test-header", "My third header");
  24. }
  25. };
  26.  
  27. //Creating a CloseableHttpClient object
  28. CloseableHttpClient httpclient = HttpClients.custom().addInterceptorFirst(responseInterceptor).build();
  29.  
  30. //Creating a request object
  31. HttpGet httpget1 = new HttpGet("https://www.tutorialspoint.com/");
  32.  
  33. //Executing the request
  34. HttpResponse httpresponse = httpclient.execute(httpget1);
  35.  
  36. //Printing remaining list of headers
  37. Header[] headers = httpresponse.getAllHeaders();
  38.  
  39. for (int i = 0; i<headers.length;i++) {
  40. System.out.println(headers[i].getName());
  41. }
  42. }
  43. }

Output

On executing, the above program generates the following result −

  1. On executing the above program generates the following output.
  2. Adding header sample_header, demo-header, test_header to the response
  3. Accept-Ranges
  4. Access-Control-Allow-Headers
  5. Access-Control-Allow-Origin
  6. Cache-Control
  7. Content-Type
  8. Date
  9. Expires
  10. Last-Modified
  11. Server
  12. Vary
  13. X-Cache
  14. sample-header
  15. demo-header
  16. test-header