Search code examples
javaspringresttemplate

Spring RestTemplate Copy property HttpHeader to RequestBody


Our application is calling other rest service using RestTemplate, its a Spring Boot application. I have some requirement where I need to copy property from http header to request body.

Doing it manually would lead to changes at many places. I am looking for a generic solution ie, I could extend the functionality of RestTemplate and use it across the application.

Is there any way to modify RestTemplate in order to achieve my requirement. I have already gone through possibilities through HttpMessageConverter, I am able to append Json Property but looking for a way where it could be copied from Header.

Please let me know if I am not clear with my requirements, any pointers would be helpful.


Solution

  • You can extend RestTemplate behaviour by implementing ClientHttpRequestInterceptor

    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;
        }
    }
    
    @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;
        }
    }
    

    Reference