如何自定义“主机" Java http客户端中的标头

编程入门 行业动态 更新时间:2024-10-14 18:21:00
本文介绍了如何自定义“主机" Java http客户端中的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的代码:

HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("127.0.0.1:8081/")) .header("Host", "test.example") .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

您可以看到它发送了两个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解决(请参见 bugs.openjdk.java/browse/JDK-8213696 ).

As of Java 12 (EA build 22) it has been solved by additional property jdk.httpclient.allowRestrictedHeaders (see bugs.openjdk.java/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客户端中的标头

本文发布于:2023-11-25 23:36:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631799.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   客户端   主机   quot   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!