我正在尝试使用JDK 11 HttpClient ,以通过需要通过登录名和密码进行身份验证的公司代理发出请求.根据JDK的简介,我正在通过以下方式构建客户端实例的:
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", 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("httpwg/asset/http.svg")) // no matter which URI to request .build(); HttpResponse<String> inResponse = httpClient.send(outRequest, BodyHandlers.ofString());但是我没有收到目标服务器的有效响应( httpwg ). 407(需要代理身份验证),即HttpClient不使用提供的authenticator.
But instead of valid response from the target server (httpwg) 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", 3128))) .build(); String encoded = new String(Base64.getEncoder().encode("login:password".getBytes())); HttpRequest outRequest = HttpRequest.newBuilder() .version(HTTP_1_1) .GET() .uri(URI.create("httpwg/asset/http.svg")) // no matter which URI to request .setHeader("Proxy-Authorization", "Basic " + encoded) .build();更多推荐
使用JDK 11 HttpClient的代理身份验证
发布评论