为 Spring RestTemplate 设置 "Host" header 不起作用
Setting "Host" header for Spring RestTemplate doesn't work
我想使用 Spring RestTemplate, via the exchange 方法发送 HTTP 请求。
第三个参数是HttpEntity
的一个实例,它允许设置请求的headers/body。我尝试了以下代码片段:
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 请求和响应服务,(在本例中)returns HTTP headers.
运行Java代码的结果如下:
{
"headers": {
"Accept": "text/plain, */*",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "whatever"
}
}
如您所见,User-Agent
设置为我想要的,但 Host
不是。
How can I set Host
to the value I desire?
也许这有帮助。我不知道底层的 http 调用是否通过 HttpUrlConnection 进行,但是将 sun.net.http.allowRestrictedHeaders 设置为 true 可能值得尝试。
参见:
我想使用 Spring RestTemplate, via the exchange 方法发送 HTTP 请求。
第三个参数是HttpEntity
的一个实例,它允许设置请求的headers/body。我尝试了以下代码片段:
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 请求和响应服务,(在本例中)returns HTTP headers.
运行Java代码的结果如下:
{
"headers": {
"Accept": "text/plain, */*",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "whatever"
}
}
如您所见,User-Agent
设置为我想要的,但 Host
不是。
How can I set
Host
to the value I desire?
也许这有帮助。我不知道底层的 http 调用是否通过 HttpUrlConnection 进行,但是将 sun.net.http.allowRestrictedHeaders 设置为 true 可能值得尝试。
参见: