How do I remove certain HTTP headers added by Spring's RestTemplate?

19,938

Chances are that's not actually the problem. My guess is that you haven't specified the correct message converter. But here is a technique to remove the headers so you can confirm that:

1. Create a custom ClientHttpRequestInterceptor implementation:

public class CustomHttpRequestInterceptor implements ClientHttpRequestInterceptor
{

   @Override
   public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException
   {
        HttpHeaders headers = request.getHeaders();
        headers.remove(HttpHeaders.CONNECTION);
        headers.remove(HttpHeaders.CONTENT_TYPE);
        headers.remove(HttpHeaders.CONTENT_LENGTH);

        return execution.execute(request, body);
    }

}

2. Then add it to the RestTemplate's interceptor chain:

@Bean
public RestTemplate restTemplate()
{

   RestTemplate restTemplate = new RestTemplate();
   restTemplate.setInterceptors(Arrays.asList(new CustomHttpRequestInterceptor(), new LoggingRequestInterceptor()));

   return restTemplate;
}
Share:
19,938

Related videos on Youtube

Psycho Punch
Author by

Psycho Punch

Updated on September 16, 2022

Comments

  • Psycho Punch
    Psycho Punch over 1 year

    I'm having a problem with a remote service I have no control over responding with HTTP 400 response to my requests sent using Spring's RestTemplate. Requests sent using curl get accepted though, so I compared them with those sent through RestTemplate. In particular, Spring requests have headers Connection, Content-Type, and Content-Length which curl requests don't. How do I configure Spring not to add those?

  • Alex78191
    Alex78191 about 6 years
    Does not work properly. Only setting headers to null works.
  • Vasia Zaretskyi
    Vasia Zaretskyi almost 3 years
    You are creating a new object 'headers' and changes are never included in the request