这是我的代码:
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
正如您所看到的,它会发送两个Host头(URI和我指定的头),但我希望它发送我指定的Host头,而不是URI中的头.
这个客户有可能吗?
编辑:在Java 11中,它变得更糟(你需要将client.send行更改为:client.send(request,HttpResponse.BodyHandlers.ofString());):
java.lang.IllegalArgumentException: restricted header name: "Host"
如何自定义该标头(测试虚拟主机所需)?
我也尝试了setHeader并得到完全相同的问题(双主机头或异常).
编辑:我报了一个JDK bug.