Sunday 19 May 2024

Add a request interceptor to Http Client

The HTTP protocol interceptor plays a crucial role in implementing specific aspects of the HTTP protocol. Typically, interceptors handle individual or groups of related headers in incoming or outgoing messages. They may also manipulate content entities enclosed within messages, often utilizing the 'Decorator' pattern to wrap the original entity.

To ensure thread safety, protocol interceptors must be implemented carefully, avoiding the use of instance variables unless synchronized.

 

The HttpRequestInterceptor interface features a process method with the following signature:

void process(HttpRequest request,
             EntityDetails entity,
             HttpContext context) throws HttpException, IOException

This method handles request processing. On the client side, it occurs before sending the request to the server, while on the server side, it operates on incoming messages before evaluating the message body. The parameters include the request itself, entity details (or null if unavailable), and the context for the request.

Define a request interceptor

private static class RequestInterceptor implements HttpRequestInterceptor {

	@Override
	public void process(HttpRequest request, EntityDetails entity, HttpContext context)
			throws HttpException, IOException {

		request.setHeader("static_secret", "secret123");

	}
}

Add Request interceptor while defining the client.

CloseableHttpClient httpClient = HttpClients
	.custom()
	.addRequestInterceptorFirst(new RequestInterceptor())
	.build();

Find the below working application.

 

RequestInterceptorDemo.java

package com.sample.app.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

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.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.EntityDetails;
import org.apache.hc.core5.http.HttpEntity;
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.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.protocol.HttpContext;

public class RequestInterceptorDemo {

	private static class RequestInterceptor implements HttpRequestInterceptor {

		@Override
		public void process(HttpRequest request, EntityDetails entity, HttpContext context)
				throws HttpException, IOException {

			request.setHeader("static_secret", "secret123");

		}
	}

	private static HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {
		@Override
		public String handleResponse(final ClassicHttpResponse response) throws IOException, ParseException {

			HttpEntity httpEntity = response.getEntity();

			try (InputStream is = httpEntity.getContent()) {
				return inputStreamToString(is, StandardCharsets.UTF_8);
			}

		}
	};

	private static String inputStreamToString(InputStream inputStream, Charset charSet) throws IOException {

		try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charSet))) {
			return reader.lines().collect(Collectors.joining("\n"));
		}

	}

	public static void main(String[] args) {
		try (CloseableHttpClient httpClient = HttpClients.custom().addRequestInterceptorFirst(new RequestInterceptor())
				.build()) {

			ClassicHttpRequest request = new HttpGet("http://localhost:8080/api/v1/replay-request");
			String response = httpClient.execute(request, responseHandler);
			System.out.println(response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Output

{"headers":{"host":"localhost:8080","static_secret":"secret123","connection":"keep-alive","accept-encoding":"gzip, x-gzip, deflate","user-agent":"Apache-HttpClient/5.3.1 (Java/1.8.0_333)"},"parameters":{},"attributes":{},"payload":""}

Methods summary

public final HttpClientBuilder addRequestInterceptorFirst(final HttpRequestInterceptor interceptor)

Adds the interceptor to the beginning of the chain, ensuring it's the first to process requests.

 

public final HttpClientBuilder addRequestInterceptorLast(final HttpRequestInterceptor interceptor)

Adds the interceptor to the end of the chain, so it processes requests after all other interceptors.

Previous                                                    Next                                                    Home

No comments:

Post a Comment