Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 201
Psycho Punch Avatar asked Aug 14 '15 08:08

Psycho Punch


Video Answer


1 Answers

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;
}
like image 175
cosbor11 Avatar answered Sep 28 '22 11:09

cosbor11