DEV Community

FelipeJansenDev
FelipeJansenDev

Posted on

Implementing an Interceptor for RestClient (Java + Spring Boot)

Hello, everyone! Today, I'll be showing you a straightforward way to set up an interceptor in the new RestClient class of the Spring Framework.

1º) First, let's create our project. We'll keep it simple, just for study purposes.

Image description

2º) Next, let's create our class that will be used as the interceptor.

@Component
public class RestClientInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().add("header1", "header 1 value");
        return execution.execute(request, body);
    }

}
Enter fullscreen mode Exit fullscreen mode

According to the Spring Framework documentation, the ClientHttpRequestInterceptor interface is a contract to intercept client-side HTTP requests. Implementations can be registered with RestClient or RestTemplate to modify the outgoing request and/or the incoming response. The interface contains the method intercept, which intercepts the given request and returns a response. The provided ClientHttpRequestExecution allows the interceptor to pass on the request and response to the next entity in the chain.

3º) Let's configure our RestClient Bean.

@Configuration
public class RestClientConfig {

    @Bean
    RestClient restClient() {
        return RestClient.builder().baseUrl(null).requestInterceptor(new RestClientInterceptor()).build();
    }
}
Enter fullscreen mode Exit fullscreen mode

4º) Now, let's create the classes to test our interceptor. We will need a service class to make HTTP requests and a test class to verify that the interceptor is working correctly.

@Service
public class Client {

    private final org.springframework.web.client.RestClient restClient;

    public Client(org.springframework.web.client.RestClient restClient) {
        this.restClient = restClient;
    }

    public void restClientAct() {
        restClient.post().retrieve();
    }

}
Enter fullscreen mode Exit fullscreen mode
@RestController
@RequestMapping("/")
public class RestClientController {

    private final Client request;

    public RestClientController(Client request) {
        this.request = request;
    }

    @GetMapping()
    public void getAccount(){
        request.restClientAct();
    }

}
Enter fullscreen mode Exit fullscreen mode

5º) Done! Here is the curl command to test the endpoint:

curl --location 'localhost:8080'

I think that's it. This basic code should address your need to intercept requests made from the RestClient.

Here's the code on github: https://github.com/FelipeJansenDev/rest-client-interceptor

Follow me on Linkedin for more tips and tricks: https://www.linkedin.com/in/felipe-neiva-jansen/

Top comments (0)