Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add http headers to RestTemplate by Interceptor or HttpEntity?

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?

like image 829
membersound Avatar asked Oct 27 '25 17:10

membersound


2 Answers

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.

like image 174
LFN Avatar answered Oct 29 '25 05:10

LFN


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()
like image 40
simerbhatti Avatar answered Oct 29 '25 06:10

simerbhatti