使用JDK 11 HttpClient的代理身份验证

编程入门 行业动态 更新时间:2024-10-22 17:29:49
本文介绍了使用JDK 11 HttpClient的代理身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用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的代理身份验证

本文发布于:2023-11-03 16:17:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555552.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:身份验证   JDK   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!