为Spring RestTemplate设置“Host”头部不起作用

6
我想使用 Spring RestTemplateexchange 方法发送HTTP请求。
第三个参数是一个 HttpEntity 实例,它允许设置请求的头和正文。我尝试了以下代码片段:
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 -cautiouslyoptimistic-
@chrylis:感谢您的评论。在我的使用情况中,我正在为某个主机H编写反向代理。代理将托管在主机H上,并通过IP联系实际主机H。但是,由于实际主机H使用虚拟主机,因此我必须在请求中指定主机名H(即从反向代理到IP地址的请求)。 - Sadeq Dousti
1个回答

2

3
非常感谢,你救了我的一天!设置 System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); 似乎完美解决了问题。 - Sadeq Dousti
3
注意!您提出了一个关于Spring RestTemplate的问题,但这个修复程序是关于Sun HttpURLConnection的。如果您使用Apache ConnectionFactory来配置RestTemplate(这是一个非常好的想法),那么这个修复程序就不相关了。 - slim
我按照这个示例重新配置了RestTemplate并使用了可以覆盖主机头的Appache http客户端,没有任何问题。 https://springframework.guru/using-resttemplate-with-apaches-httpclient/ - NewestStackOverflowUser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接