使用Java httpClient时,我试图设置主机头。我发现可以使用setVirtualHost在apache httpClient中完成。我该如何使用Java httpClient做同样的事情。
答案 0 :(得分:0)
如果发送请求,则会自动设置主机头。以下程序向GET
发送httpbin.org/headers
请求,并显示到达服务器端的标头。
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Test {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://httpbin.org/headers"))
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
该程序的输出为
{
"headers": {
"Content-Length": "0",
"Host": "httpbin.org",
"Http2-Settings": "AAEAAEAAAAIAAAABAAMAAABkAAQBAAAAAAUAAEAA",
"Upgrade": "h2c",
"User-Agent": "Java-http-client/11.0.2",
"X-Amzn-Trace-Id": "Root=1-5e89b28a-7028ca70c49af58d120493b1"
}
}
您可以通过定义另一个URI来更改Host
字段的值,例如如果使用URI http://www.httpbin.org/headers
,则Host标头字段的值为www.httpbin.org
。
Host
标头不能单独设置。在类jdk.internal.net.http.common.Utils
中定义了一组不允许的标头。
private static final Set<String> DISALLOWED_HEADERS_SET;
static {
// A case insensitive TreeSet of strings.
TreeSet<String> treeSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
treeSet.addAll(Set.of("connection", "content-length",
"date", "expect", "from", "host", "upgrade", "via", "warning"));
DISALLOWED_HEADERS_SET = Collections.unmodifiableSet(treeSet);
}