logo头像
Snippet 博客主题

HTTP请求设置代理

HTTP请求设置代理


1. HttpURLConnection配置代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
URL httpUrl = new URL("www.baidu.com");  // 创建URL实例

// 通过代理服务器的ip和端口构建一个 网络编程类InetSocketAddress
// hostname:ip,port:端口
InetSocketAddress addr = new InetSocketAddress("127.0.0.1","80");

// 创建代理对象
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);

// 打开一个http的连接
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection(proxy);

// 设置代理服务的账号和密码,如果是无需验证的Proxy 请忽略
String encoded = new String(org.apache.commons.codec.binary.Base64.encodeBase64(new String("admin" + ":" + "admin").getBytes()));
conn.setRequestProperty("Proxy-Authorization", "Basic " + encoded);

// 设置连接时间
conn.setConnectTimeout(5000);
  • 注意: 到这一步其实还没有完,在这一步进行发送配置的代理的http请求会得到一个
  • Server returned HTTP response code: 407 错误
  • 这个错误的原因是:如果代理服务需要配置账号和密码验证,会在请求Http的时候需要你再次验证网络连接的身份
1
2
3
4
5
6
7
8
9
// username:代理服务器账号
// password:代理服务器密码,需要转成char[]
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password.toCharArray()
);
}
});

通过创建 Authenticator 当需要身份验证时,系统将调用该子类上的方法(如getPasswordAuthentication)子类的方法可以使用许多继承的方法(getRequestingXXX())查询请求的身份验证,并为用户形成适当的消息。

上一篇
Fork me on GitHub