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

M.S*_*sti 6 java rest spring resttemplate

我想通过交换方法使用Spring RestTemplate发送 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

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

运行Java代码的结果如下:

{
  "headers": {
    "Accept": "text/plain, */*", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "whatever"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 4

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

看:

  • 非常感谢; 你救了我的命!设置 `System.setProperty("sun.net.http.allowRestrictedHeaders", "true");` 似乎工作得很好。 (3认同)
  • 谨防!您提出了有关 Spring RestTemplate 的问题,但此修复是有关 Sun HttpURLConnection 的。如果您使用 Apache ConnectionFactory 配置 RestTemplate(这是一个非常好的主意),则此修复变得无关紧要。 (3认同)