Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

http2 - How to customise "host" header in Java http client

Here's my code:

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());

As a result I see that the above code sends:

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

As you can see it sends two Host headers (the one from URI and the one I specified), but I would like it to send the Host header that I specified, not the one from the URI. Is it possible with this client?

EDIT: In Java 11, it gets even worse (you need to change the client.send line to: client.send(request, HttpResponse.BodyHandlers.ofString());):

java.lang.IllegalArgumentException: restricted header name: "Host"

How can I customize that header (needed for testing of virtual hosts)?

I also tried the setHeader and get exactly the same problem (either double Host headers, or the exception).

EDIT: I reported a JDK bug.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of Java 12 (EA build 22) it has been solved by additional property jdk.httpclient.allowRestrictedHeaders (see https://bugs.openjdk.java.net/browse/JDK-8213696).

So now one can override Host (or any other restricted header) by executing the code with: java -Djdk.httpclient.allowRestrictedHeaders=host ...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...