使用JDK 11 HttpClient的代理身份验证 [英] Proxy Authentication with JDK 11 HttpClient
问题描述
我正在尝试使用JDK 11 简介,我正在通过以下方式构建客户端实例的:
I'm trying to use JDK 11 HttpClient to make requests through a corporate proxy which requires authentication by login and password. According to JDK's intro, I'm building an instance of client by means of:
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 ). 407(需要代理身份验证),即HttpClient
不使用提供的authenticator
.
But instead of valid response from the target server (https://httpwg.org) I receive HTTP 407 (Proxy Authentication Required), i.e. HttpClient
does not use the provided authenticator
.
I've tried various solutions mentioned here and here but none of them helped.
使其正常工作的正确方法是什么?
What is the correct way to make it work?
推荐答案
您必须在请求中设置代理授权"标头.
You have to set the "Proxy-Authorization" header on the request.
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();
这篇关于使用JDK 11 HttpClient的代理身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!