gpt4 book ai didi

java - 为 Spring RestTemplate 设置 "Host" header 不起作用

转载 作者:行者123 更新时间:2023-11-30 06:48:43 29 4
gpt4 key购买 nike

我想使用 Spring RestTemplate 发送 HTTP 请求,通过exchange方法。

第三个参数是HttpEntity的实例,它允许设置请求的 header /正文。我尝试了以下代码片段:

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 header 。

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 可能值得尝试。

参见:

关于java - 为 Spring RestTemplate 设置 "Host" header 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43223261/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com