【问题标题】:Setting "Host" header for Spring RestTemplate doesn't work为 Spring RestTemplate 设置“Host”标头不起作用
【发布时间】:2017-04-05 06:18:35
【问题描述】:

我想通过exchange 方法使用Spring RestTemplate 发送一个HTTP 请求。

第三个参数是HttpEntity的一个实例,它允许设置请求的headers/body。我尝试了以下代码sn-p:

import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

public class Connector {
    public static void main(String[] args) {

        HttpHeaders headers = new HttpHeaders();
        headers.set("Host", "www.example.com");
        headers.set("User-Agent", "whatever");


        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> responseEntity = restTemplate.exchange(
                "http://httpbin.org/headers", HttpMethod.GET,
                new HttpEntity<String>(null, headers), String.class);

        System.out.println(responseEntity.getBody());
    }
}

请注意,http://httpbin.org/headers 是一个简单的 HTTP 请求和响应服务,它(在本例中)返回 HTTP 标头。

运行Java代码的结果如下:

{
  "headers": {
    "Accept": "text/plain, */*", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "whatever"
  }
}

如您所见,User-Agent 设置为我想要的,但Host 不是。

如何将Host 设置为我想要的值?

【问题讨论】:

  • 我不确定你能不能 - 将 Host 标头设置为与 URI 不同的东西通常没有意义。
  • @chrylis:感谢您的评论。在我的用例中,我正在为某个主机 H 编写反向代理。代理将托管在主机 H 上,并将通过 IP 联系实际的主机 H。但是,由于实际主机 H 使用虚拟主机,我必须在请求中指定主机名 H(即从反向代理到 IP 地址的请求)。

标签: java spring rest resttemplate


【解决方案1】:

也许这会有所帮助。我不知道底层的 http 调用是否是通过 HttpUrlConnection 进行的,但是将 sun.net.http.allowRestrictedHeaders 设置为 true 可能值得一试。

见:

【讨论】:

  • 非常感谢;你救了我的一天!设置System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); 似乎效果很好。
  • 当心!你问过一个关于 Spring RestTemplate 的问题,但这个修复是关于 Sun HttpURLConnection。如果您使用 Apache ConnectionFactory 配置 RestTemplate(这是一个非常好的主意),则此修复将变得无关紧要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 2013-10-14
  • 1970-01-01
  • 2020-01-04
相关资源
最近更新 更多