java 如何删除 Spring 的 RestTemplate 添加的某些 HTTP 标头?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32005513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I remove certain HTTP headers added by Spring's RestTemplate?
提问by Psycho Punch
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?
我在使用远程服务时遇到问题,我无法控制对使用 Spring 的 RestTemplate 发送的请求的 HTTP 400 响应。使用发送的请求curl
虽然被接受,所以我将它们与通过 RestTemplate 发送的请求进行了比较。特别是春天的要求有头Connection
,Content-Type
以及Content-Length
其curl
请求不。如何配置 Spring 不添加这些?
回答by cosbor11
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:
1. 创建自定义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's interceptor chain:
2.然后将其添加到RestTemplate的拦截器链中:
@Bean
public RestTemplate restTemplate()
{
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(Arrays.asList(new CustomHttpRequestInterceptor(), new LoggingRequestInterceptor()));
return restTemplate;
}