如何在 Java http 客户端中自定义“host”标头
2022-09-04 03:06:36
这是我的代码:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://127.0.0.1:8081/"))
.header("Host", "test.example.com")
.build();
client.send(request, HttpResponse.BodyHandlers.ofString());
结果,我看到上面的代码发送:
GET / HTTP/1.1
Connection: Upgrade, HTTP2-Settings
Content-Length: 0
Host: 127.0.0.1:8081
HTTP2-Settings: AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA
Upgrade: h2c
User-Agent: Java-http-client/10
Host: test.example.com
如您所见,它发送两个标头(来自URI的标头和我指定的标头),但我希望它发送我指定的标头,而不是来自URI的标头。这个客户端可能吗?Host
Host
编辑:在Java 11中,情况变得更糟(您需要将 client.send 行更改为:):client.send(request, HttpResponse.BodyHandlers.ofString());
java.lang.IllegalArgumentException: restricted header name: "Host"
如何自定义该标头(测试虚拟主机时需要)?
我也尝试了并得到完全相同的问题(双头或异常)。setHeader
Host
编辑:我报告了一个JDK错误。