我正在发送带有以下代码的邮寄请求。
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddr, proxyPort));
URLConnection urlConnection = url.openConnection(proxy);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
...
这里我可以设置代理服务器的地址和端口。但是我不知道如何在这里添加代理用户名和密码。
我读了一些有关通过代理调用http请求的文章,但没有人谈论代理身份验证。
希望你们提供一些帮助。
有人建议使用here中的代码
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("user",
"password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
但是这根本不起作用。
最后我想通了。
向请求添加了授权标题。
String credential = Credentials.basic(proxyUsername, proxyPassword);
urlConnection.addRequestProperty("Proxy-Authorization", credential);