我试图使用JDK 11 HttpClient通过公司代理发出请求,这需要通过登录和密码进行身份验证。根据JDK的简介,我正在通过以下方法构建客户机实例:
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)的有效响应,而是接收HTTP407(所需的代理身份验证),即HttpClient不使用提供的authenticator。
什么是正确的方法使它工作?
发布于 2020-02-11 13:43:05
您必须在请求中设置“代理授权”头。
HttpClient httpClient = HttpClient.newBuilder()
.version(HTTP_1_1)
.proxy(ProxySelector.of(new InetSocketAddress("proxy.mycompany.com", 3128)))
.build();
String encoded = new String(Base64.getEncoder().encode("login:password".getBytes()));
HttpRequest outRequest = HttpRequest.newBuilder()
.version(HTTP_1_1)
.GET()
.uri(URI.create("https://httpwg.org/asset/http.svg")) // no matter which URI to request
.setHeader("Proxy-Authorization", "Basic " + encoded)
.build();发布于 2018-11-16 11:56:34
默认情况下,从java 8u111开始通过身份验证代理隧道时,将禁用与代理的基本身份验证。
您可以通过在java命令行上指定-Djdk.http.auth.tunneling.disabledSchemes=""来重新启用它。
发布于 2022-09-19 18:55:15
使用
System.setProperty("jdk.http.auth.proxying.disabledSchemes", "");
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");使用代理选择器和身份验证器构造http客户端
HttpClient client = HttpClient.newBuilder()
.authenticator(yourCustomAuthenticator)
.proxy(yourCustomProxySelector)
.build();在身份验证覆盖中
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType().equals(RequestorType.PROXY)) {
return getPasswordAuthentication(getRequestingHost());
} else {
return null;
}
}
protected PasswordAuthentication getPasswordAuthentication(String proxyHost) {
// your logic to find username and password for proxyHost
return new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray());
// or return null
}https://stackoverflow.com/questions/53333556
复制相似问题