Course – LS (cat=HTTP Client-Side)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’re going to learn how to implement a Spring RestTemplate Interceptor.

We’ll go through an example in which we’ll create an interceptor that adds a custom header to the response.

2. Interceptor Usage Scenarios

Besides header modification, some of the other use-cases where a RestTemplate interceptor is useful are:

  • Request and response logging
  • Retrying the requests with a configurable back off strategy
  • Request denial based on certain request parameters
  • Altering the request URL address

3. Creating the Interceptor

In most programming paradigms, interceptors are an essential part that enables programmers to control the execution by intercepting it. Spring framework also supports a variety of interceptors for different purposes.

Spring RestTemplate allows us to add interceptors that implement ClientHttpRequestInterceptor interface. The intercept(HttpRequest, byte[], ClientHttpRequestExecution) method of this interface will intercept the given request and return the response by giving us access to the request, body and execution objects.

We’ll be using the ClientHttpRequestExecution argument to do the actual execution, and pass on the request to the subsequent process chain.

As a first step, let’s create an interceptor class that implements the ClientHttpRequestInterceptor interface:

public class RestTemplateHeaderModifierInterceptor
  implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(
      HttpRequest request, 
      byte[] body, 
      ClientHttpRequestExecution execution) throws IOException {
 
        ClientHttpResponse response = execution.execute(request, body);
        response.getHeaders().add("Foo", "bar");
        return response;
    }
}

Our interceptor will be invoked for every incoming request, and it will add a custom header Foo to every response, once the execution completes and returns.

Since the intercept() method included the request and body as arguments, it’s also possible to do any modification on the request or even denying the request execution based on certain conditions.

4. Setting up the RestTemplate

Now that we have created our interceptor, let’s create the RestTemplate bean and add our interceptor to it:

@Configuration
public class RestClientConfig {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();

        List<ClientHttpRequestInterceptor> interceptors
          = restTemplate.getInterceptors();
        if (CollectionUtils.isEmpty(interceptors)) {
            interceptors = new ArrayList<>();
        }
        interceptors.add(new RestTemplateHeaderModifierInterceptor());
        restTemplate.setInterceptors(interceptors);
        return restTemplate;
    }
}

In some cases, there might be interceptors already added to the RestTemplate object. So to make sure everything works as expected, our code will initialize the interceptor list only if it’s empty.

As our code shows, we are using the default constructor to create the RestTemplate object, but there are some scenarios where we need to read the request/response stream twice.

For instance, if we want our interceptor to function as a request/response logger, then we need to read it twice – the first time by the interceptor and the second time by the client.

The default implementation allows us to read the response stream only once. To cater such specific scenarios, Spring provides a special class called BufferingClientHttpRequestFactory. As the name suggests, this class will buffer the request/response in JVM memory for multiple usage.

Here’s how the RestTemplate object is initialized using BufferingClientHttpRequestFactory to enable the request/response stream caching:

RestTemplate restTemplate 
  = new RestTemplate(
    new BufferingClientHttpRequestFactory(
      new SimpleClientHttpRequestFactory()
    )
  );

5. Testing Our Example

Here’s the JUnit test case for testing our RestTemplate interceptor:

public class RestTemplateItegrationTest {
    
    @Autowired
    RestTemplate restTemplate;

    @Test
    public void givenRestTemplate_whenRequested_thenLogAndModifyResponse() {
        LoginForm loginForm = new LoginForm("username", "password");
        HttpEntity<LoginForm> requestEntity
          = new HttpEntity<LoginForm>(loginForm);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        ResponseEntity<String> responseEntity
          = restTemplate.postForEntity(
            "http://httpbin.org/post", requestEntity, String.class
          );
        
        Assertions.assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);
        Assertions.assertEquals(responseEntity.getHeaders()
                .get("Foo")
                .get(0), "bar");
    }
}

Here, we’ve used the freely hosted HTTP request and response service http://httpbin.org to post our data. This testing service will return our request body along with some metadata.

6. Conclusion

This tutorial is all about how to set up an interceptor and add it to the RestTemplate object. This kind of interceptors can also be used for filtering, monitoring and controlling the incoming requests.

A common use-case for a RestTemplate interceptor is the header modification – which we’ve illustrated in details in this article.

And, as always, you can find the example code over on Github project. This is a Maven-based project, so it should be easy to import and run as it is.

Course – LS (cat=HTTP Client-Side)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – HTTP Client (eBook) (cat=Http Client-Side)
Comments are closed on this article!