设置“主机"Spring RestTemplate 的标头不起作用
我想使用 Spring RestTemplate,通过 交换 方法.
I want to send an HTTP request using Spring RestTemplate, via the exchange method.
第三个参数是 HttpEntity
的一个实例,它允许设置请求的头部/主体.我尝试了以下代码片段:
The third parameter is an instance of HttpEntity
, which allows setting the headers/body of the request. I tried the following code snippet:
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 标头.
Notice that http://httpbin.org/headers is a simple HTTP Request & Response Service, which (in this case) returns HTTP headers.
运行Java代码的结果如下:
The result of running the Java code is as follows:
{
"headers": {
"Accept": "text/plain, */*",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "whatever"
}
}
如您所见,User-Agent
设置为我想要的,但 Host
不是.
As you can see, the User-Agent
is set to what I wanted, but the Host
is not.
如何将 Host
设置为我想要的值?
How can I set
Host
to the value I desire?
也许这会有所帮助.我不知道底层 http 调用是否通过 HttpUrlConnection 进行,但将 sun.net.http.allowRestrictedHeaders 设置为 true 可能值得尝试.
Perhaps this helps. I don't know if the underlying http call is made through HttpUrlConnection, but setting sun.net.http.allowRestrictedHeaders to true might be worth trying.
见: