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?
1)
HttpEntitydirectly before sending: fine-grained control of the restTemplate. It works but you must repeat the code everywhere and the developer may forget it (DRY)2)
ClientHttpRequestInterceptorwithRestTemplateCustomizer: Each restTemplate created from restTemplateBuilder bean will have this interceptor, suitable for a general behavior.