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?
Asked
Active
Viewed 2.5k times
12

Psycho Punch
- 6,418
- 9
- 53
- 86
-
This answer might be useful http://stackoverflow.com/questions/16339576/remove-http-response-headers-in-java – clbcabral Aug 14 '15 at 12:40
-
What error/response code are you getting? 401 Unauthorized? – cosbor11 Dec 31 '15 at 18:49
1 Answers
5
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;
}

cosbor11
- 14,709
- 10
- 54
- 69
-
3Does not work properly. Only [setting headers to null](https://stackoverflow.com/a/31021757) works. – Alex78191 Apr 09 '18 at 16:29
-
2You are creating a new object 'headers' and changes are never included in the request – Vasia Zaretskyi Jun 02 '21 at 12:20