Psycho Punch
Psycho Punch

Reputation: 6892

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?

Upvotes: 11

Views: 29447

Answers (1)

cosbor11
cosbor11

Reputation: 16024

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;
}

Upvotes: 5

Related Questions