为春季休息模板设置"Host"标题不起作用



我想通过交换方法使用 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());
    }
}

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

运行 Java 代码的结果如下:

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

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

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

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

看:

  • 我可以在使用java的HttpUrlConnection类的地方覆盖主机头吗?
  • 如何在 HttpURL 容器中覆盖 http-header "Host"?

最新更新