If I have some static headers that should be applied to any request sending with RestTemplate: how should those be added?
In this example, I'd always want to sent the http header accept=applicaton/json. (it could as well be any other header, also multiple ones).
1) HttpEntity directly before sending:
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
ResponseEntity<Rsp> http = restTemplate.postForEntity(host, new HttpEntity<>(req, headers), type);
2) ClientHttpRequestInterceptor:
class MyInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
return execution.execute(request, body);
}
}
@Bean
public RestTemplateCustomizer customizer() {
return restTemplate -> restTemplate.getInterceptors().add(new MyInterceptor());
}
And then just post:
restTemplate.postForEntity(host, req, type);
Which one has an advantage over the other, and should thus be preferred?
Option 1 seems a little hard to maintain since the developer would need to remember to do it every time. Option 2 would be better, I would only do the following change:
Where you do
restTemplate.getInterceptors().add(new MyInterceptor())
I would do
List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
if (CollectionUtils.isEmpty(interceptors)) {
interceptors = new ArrayList<>();
}
interceptors.add(new MyInterceptor());
restTemplate.setInterceptors(interceptors);
This way you can initialize the list in case it's empty.
Also, be careful because someone can set a new interceptor list to the bean and lose yours.
Java 8 Lambda way of doing it with interceptor
new RestTemplateBuilder().interceptors(
(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> {
request.getHeaders().set(AUTHORIZATION, token);
return execution.execute(request, body);
}
).build()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With