我尝试使用JDK-11 HttpClient 修改Referer 标头。
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Test {
public static final void main(final String[] argc) throws IOException, InterruptedException {
final HttpClient client = HttpClient.newHttpClient();
final HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://suche.org/refererDemo"))
.header("Referer", "google.com")
.build();
final HttpResponse<String> ret = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("ret: "+ret.body());
}
}
但我收到错误:
Exception in thread "main" java.lang.IllegalArgumentException: restricted header name: "Referer"
at java.net.http/jdk.internal.net.http.common.Utils.newIAE(Utils.java:246)
at java.net.http/jdk.internal.net.http.HttpRequestBuilderImpl.checkNameAndValue(HttpRequestBuilderImpl.java:110)
at java.net.http/jdk.internal.net.http.HttpRequestBuilderImpl.header(HttpRequestBuilderImpl.java:126)
at java.net.http/jdk.internal.net.http.HttpRequestBuilderImpl.header(HttpRequestBuilderImpl.java:43)
at Test.main(Test.java:12)
通常我希望应该接受任何有效的主机。因为这用于某些方面的访问控制。这是一个错误还是有设置引用者的新方法?
这个问题与关于“主机”标题的问题有两种不同。主机头是根据 url 设置的。这可以通过 dns 或 etc/host 解析进行修改。这对于“Referer”是不可能的,因为客户端不知道导致此调用的先前主机或 URL。即使该值有效,它也会被拒绝。它可以是: - 完整 URL - 没有路径的 URL - 仅域名