Apache HttpClient - Interceptors


Advertisements

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.

HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {

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

Step 2 - Instantiate CloseableHttpClient object

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

//Creating a CloseableHttpClient object
CloseableHttpClient httpclient =
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.

import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HttpContext;

public class InterceptorsExample {
 
   public static void main(String args[]) throws Exception{
      
      //Creating an HttpRequestInterceptor
      HttpRequestInterceptor requestInterceptor = new HttpRequestInterceptor() {
         @Override
         public void process(HttpRequest request, HttpContext context) throws
         HttpException, IOException {
            if(request.containsHeader("sample-header")) {
               System.out.println("Contains header sample-header, removing it..");
               request.removeHeaders("sample-header"); 
            }
            //Printing remaining list of headers
            Header[] headers= request.getAllHeaders();
            for (int i = 0; i<headers.length;i++) {
               System.out.println(headers[i].getName());
            }
         }
      };

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

      //Creating a request object
      HttpGet httpget1 = new HttpGet("https://www.tutorialspoint.com/");

      //Setting the header to it
      httpget1.setHeader(new BasicHeader("sample-header","My first header"));
      httpget1.setHeader(new BasicHeader("demo-header","My second header"));
      httpget1.setHeader(new BasicHeader("test-header","My third header"));

      //Executing the request
      HttpResponse httpresponse = httpclient.execute(httpget1);

      //Printing the status line
      System.out.println(httpresponse.getStatusLine());
   }
}

Output

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

Contains header sample-header, removing it..
demo-header
test-header
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.

HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
   @Override
   public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
      //Method implementation . . . . . . . .
   }
};

Step 2: Instantiate CloseableHttpClient object

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

//Creating a CloseableHttpClient object
CloseableHttpClient httpclient =
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.

import java.io.IOException;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;

public class ResponseInterceptorsExample {

   public static void main(String args[]) throws Exception{
      
      //Creating an HttpRequestInterceptor
      HttpResponseInterceptor responseInterceptor = new HttpResponseInterceptor() {
         @Override
         public void process(HttpResponse response, HttpContext context) throws
         HttpException, IOException {
            System.out.println("Adding header sample_header, demo-header, test_header to the response");
            response.setHeader("sample-header", "My first header");
            response.setHeader("demo-header", "My second header");
            response.setHeader("test-header", "My third header"); 
         }
      };

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

      //Creating a request object
      HttpGet httpget1 = new HttpGet("https://www.tutorialspoint.com/");

      //Executing the request
      HttpResponse httpresponse = httpclient.execute(httpget1); 

      //Printing remaining list of headers
      Header[] headers = httpresponse.getAllHeaders();
 
      for (int i = 0; i<headers.length;i++) {
         System.out.println(headers[i].getName());
      }
   }
}

Output

On executing, the above program generates the following result −

On executing the above program generates the following output.
Adding header sample_header, demo-header, test_header to the response
Accept-Ranges
Access-Control-Allow-Headers
Access-Control-Allow-Origin
Cache-Control
Content-Type
Date
Expires
Last-Modified
Server
Vary
X-Cache
sample-header
demo-header
test-header
Advertisements