如何自定义“主机" Java http客户端中的标头 [英] How to customise "host" header in Java http client

查看:294
本文介绍了如何自定义“主机" Java http客户端中的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

您可以看到它发送了两个Host标头(一个来自URI,另一个是我指定的),但是我希望它发送我指定的Host标头,而不是发送来自URI的一个. 这个客户可以吗?

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?

在Java 11中,情况甚至更糟(您需要将client.send行更改为:client.send(request, HttpResponse.BodyHandlers.ofString());):

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)?

我也尝试过setHeader并得到完全相同的问题(双Host标头或异常).

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

我报告了一个 JDK错误.

推荐答案

从Java 12(EA内部版本22)开始,它已由其他属性jdk.httpclient.allowRestrictedHeaders解决(请参见

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).

因此,现在可以通过执行以下代码来覆盖Host(或任何其他受限制的标头): java -Djdk.httpclient.allowRestrictedHeaders=host ...

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

这篇关于如何自定义“主机" Java http客户端中的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆