Search code examples
spring-bootresttemplate

Adding a header to every call using RestTemplate


I want to call a third party API and in order to do so I have to send my subscription key. I tried to add to RestTemplate via bean config but it doesn't seem to work.

@Configuration
public class RequestHeaderConfig {

    private ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {
        ClientHttpResponse response = execution.execute(request, body);
        response.getHeaders().add("Subscription","9999999-999b-4999-99995-9999999999d");
        return response;

    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(this::intercept));
        return restTemplate;
    }

}

Then I autowire it in the constructor:

@Autowired
public Service(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
}

and use it here:

restTemplate.exchange(builder.toUriString(), HttpMethod.GET, request, String.class);

Advice?


Solution

  • call a third party API and in order to do so I have to send my subscription key.

    You should set the header on the request object not on the response.

          private ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                                ClientHttpRequestExecution execution) throws IOException {
                request.getHeaders().add("Subscription","9999999-999b-4999-99995-9999999999d");
                ClientHttpResponse response = execution.execute(request, body);
                return response;
    
            }