【问题标题】:How do I remove certain HTTP headers added by Spring's RestTemplate?如何删除 Spring 的 RestTemplate 添加的某些 HTTP 标头?
【发布时间】:2015-11-07 10:35:24
【问题描述】:

我的远程服务出现问题,我无法控制对使用 Spring 的 RestTemplate 发送的请求进行 HTTP 400 响应。不过,使用curl 发送的请求会被接受,因此我将它们与通过 RestTemplate 发送的请求进行了比较。特别是,Spring 请求具有标题 ConnectionContent-TypeContent-Length,而 curl 请求没有。如何配置 Spring 不添加这些?

【问题讨论】:

标签: java spring spring-mvc resttemplate


【解决方案1】:

这实际上并不是问题所在。我的猜测是您没有指定正确的消息转换器。但这里有一种删除标题的技术,因此您可以确认:

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。然后将其添加到 RestTemplate 的拦截器链中:

@Bean
public RestTemplate restTemplate()
{

   RestTemplate restTemplate = new RestTemplate();
   restTemplate.setInterceptors(Arrays.asList(new CustomHttpRequestInterceptor(), new LoggingRequestInterceptor()));

   return restTemplate;
}

【讨论】:

  • 无法正常工作。只有setting headers to null 有效。
  • 您正在创建一个新对象“标头”,并且更改永远不会包含在请求中
猜你喜欢
  • 1970-01-01
  • 2014-04-24
  • 2015-12-13
  • 2020-02-11
  • 2018-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多