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");
InetSocketAddress addr = new InetSocketAddress("127.0.0.1","80");
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection(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
|
Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray() ); } });
|
通过创建 Authenticator 当需要身份验证时,系统将调用该子类上的方法(如getPasswordAuthentication)子类的方法可以使用许多继承的方法(getRequestingXXX())查询请求的身份验证,并为用户形成适当的消息。