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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With