如何配置用户名和密码以使用 Java 对 http 代理服务器进行身份验证?
我刚刚找到以下配置参数:
http.proxyHost=<proxyAddress>
http.proxyPort=<proxyPort>
https.proxyHost=<proxyAddress>
https.proxyPort=<proxyPort>
但是,我的代理服务器需要身份验证。如何配置我的应用以使用代理服务器?
最佳答案
(编辑:正如 OP 所指出的,也需要使用 java.net.Authenticator
。为了正确起见,我正在相应地更新我的答案。)
(EDIT#2: 正如 another answer 中指出的那样,在 JDK 8 中,需要从 jdk.http.auth.tunneling.disabledSchemes
中删除 basic
身份验证方案属性)
对于身份验证,使用java.net.Authenticator
设置代理的配置并设置系统属性http.proxyUser
和http.proxyPassword
。
final String authUser = "user";
final String authPassword = "password";
Authenticator.setDefault(
new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(authUser, authPassword.toCharArray());
}
}
);
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
关于java - 使用 Java 进行身份验证的 HTTP 代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1626549/