我正在尝试使用 JDK 11 HttpClient通过需要通过登录名和密码进行身份验证的公司代理发出请求。根据 JDK 的 intro ,我正在通过以下方式构建客户端实例:
HttpClient httpClient = HttpClient.newBuilder()
.version(HTTP_1_1)
.proxy(ProxySelector.of(new InetSocketAddress("proxy.mycompany.com", 3128)))
.authenticator(authenticator)
.build();
,其中
authenticator
是:Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("login", "password".toCharArray());
}
};
然后我执行请求本身:
HttpRequest outRequest = HttpRequest.newBuilder()
.version(HTTP_1_1)
.GET()
.uri(URI.create("https://httpwg.org/asset/http.svg")) // no matter which URI to request
.build();
HttpResponse<String> inResponse = httpClient.send(outRequest, BodyHandlers.ofString());
但不是来自目标服务器的有效响应( https://httpwg.org ),我收到 HTTP 407(需要代理身份验证),即
HttpClient
不使用提供的 authenticator
.我尝试了各种提到的解决方案 here和 here但他们都没有帮助。
使它工作的正确方法是什么?
最佳答案
默认情况下,从 java 8u111 开始,当通过身份验证代理进行隧道传输时,将禁用使用代理的基本身份验证。
您可以通过指定 -Djdk.http.auth.tunneling.disabledSchemes=""
重新启用它在 java 命令行上。
见 jdk 8u111 release notes
关于java - 使用 JDK 11 HttpClient 进行代理身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333556/