【发布时间】:2017-04-05 06:18:35
【问题描述】:
我想通过exchange 方法使用Spring RestTemplate 发送一个HTTP 请求。
第三个参数是HttpEntity的一个实例,它允许设置请求的headers/body。我尝试了以下代码sn-p:
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:感谢您的评论。在我的用例中,我正在为某个主机 H 编写反向代理。代理将托管在主机 H 上,并将通过 IP 联系实际的主机 H。但是,由于实际主机 H 使用虚拟主机,我必须在请求中指定主机名 H(即从反向代理到 IP 地址的请求)。
标签: java spring rest resttemplate