在发起HTTP请求(openConnection() 或者 openStream())之前,加上以下2行代码
System.setProperty("proxyHost", "127.0.0.1"); // PROXY_HOST:代理的IP地址
System.setProperty("proxyPort", "10809"); // PROXY_PORT:代理的端口号
代理需要验证
Authenticator.setDefault(new BasicAuthenticator(PROXY_USERNAME, PROXY_PASSWORD));
class BasicAuthenticator extends Authenticator {
private String userName;
private String password;
public BasicAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}
/**
* Called when password authorization is needed. Subclasses should
* override the default implementation, which returns null.
*
* @return The PasswordAuthentication collected from the
* user, or null if none is provided.
*/
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password.toCharArray());
}
}