我正在尝试使用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
。
正确的方法是什么?
-Djava.net.useSystemProxies=true
吗? - Marco Carlo Moriggi