0

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?

1
  • BTW, RestTemplate is going to be deprecated in future versions of Spring. They suggest to use WebClient API introduced in Spring 5. Check RestTempalte JavaDoc. Commented Feb 20, 2019 at 8:23

1 Answer 1

3

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;

        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.