这是我的代码:
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.BodyHandler.asString());
结果我看到上面的代码发送:
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
并得到完全相同的问题(双头Host
或异常)
发布于 2018-10-11 10:36:40
ava11客户端代码的行为似乎是正确的。该主机部分阐述了细节。顺便说一下,从HttpRequest
构建器的文档header(String name, String value)
:
* @throws IllegalArgumentException if the header name or value is not
* valid, see <a href="https://tools.ietf.org/html/rfc7230#section-3.2">
* RFC 7230 section-3.2</a>, or the header name or value is restricted
* by the implementation.
https://stackoverflow.com/questions/-100005063
复制相似问题