How to remove specific HTTP headers added by Spring RestTemplate?

I have a problem with a remote service. I have no control over the HTTP 400 response to my requests sent using Spring RestTemplate. Requests sent using curl are accepted, however, so I compared them with messages sent via RestTemplate. In particular, Spring requests have Connection , Content-Type and Content-Length headers that curl does not request. How to configure Spring not to add them?

+6
source share
1 answer

This is most likely not a problem. I assume that you did not specify the correct message converter. But here is the header removal technique so you can confirm that:

1. Create a custom implementation of ClientHttpRequestInterceptor :

 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 chain of interceptors:

 @Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); restTemplate.setInterceptors(Arrays.asList(new CustomHttpRequestInterceptor(), new LoggingRequestInterceptor())); return restTemplate; } 
+4
source

All Articles