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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:30:06  来源:igfitidea点击:

How do I remove certain HTTP headers added by Spring's RestTemplate?

javaspringspring-mvcresttemplate

提问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 curlget accepted though, so I compared them with those sent through RestTemplate. In particular, Spring requests have headers Connection, Content-Type, and Content-Lengthwhich curlrequests don't. How do I configure Spring not to add those?

我在使用远程服务时遇到问题,我无法控制对使用 Spring 的 RestTemplate 发送的请求的 HTTP 400 响应。使用发送的请求curl虽然被接受,所以我将它们与通过 RestTemplate 发送的请求进行了比较。特别是春天的要求有头ConnectionContent-Type以及Content-Lengthcurl请求不。如何配置 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 ClientHttpRequestInterceptorimplementation:

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