Java-HTTP连接时如何使用代理(一)—— System.Property方式

在发起HTTP请求(openConnection() 或者 openStream())之前,加上以下2行代码:

1 System.setProperty("proxyHost", PROXY_HOST); // PROXY_HOST:代理的IP地址
2 System.setProperty("proxyPort",  PROXY_PORT); // PROXY_PORT:代理的端口号

 

如果你的代理不需要通过验证(输入用户名和密码),那么就不用继续往下读了。

 

★ 代理需要验证

如果你想当然地认为加上以下两行代码就行,那就错了。

1 System.setProperty("proxyUser", PROXY_USERNAME); // 或者 System.setProperty("proxyUsername", PROXY_USERNAME);
2 System.setProperty("proxyPassword", PROXY_PASSWORD);

 

这时就需要 java.net.Authenticator 类来完成一般的Http验证

在发起请求之前加人如下代码即可:

1 Authenticator.setDefault(new BasicAuthenticator(PROXY_USERNAME, PROXY_PASSWORD));

 

当然,还需要创建一个类 BasicAuthenticator,继承自 java.net.Authenticator

 1 class BasicAuthenticator extends Authenticator { 
 2         private String userName; 
 3         private String password; 
 4       
 5         public BasicAuthenticator(String userName, String password) { 
 6             this.userName = userName; 
 7             this.password = password; 
 8         } 
 9       
10         /** 
11          * Called when password authorization is needed. Subclasses should 
12          * override the default implementation, which returns null. 
13          * 
14          * @return The PasswordAuthentication collected from the 
15          * user, or null if none is provided. 
16          */ 
17         @Override 
18         protected PasswordAuthentication getPasswordAuthentication() { 
19             return new PasswordAuthentication(userName, password.toCharArray()); 
20         } 
21     }

 


 

详细代码可参考笔者在GitHub上的代码,包括实现类和测试类:

实现类:
https://github.com/YoungZHU/CollectionCode4Java/blob/master/src/org/young/util/ProxyedURL.java

测试类:

https://github.com/YoungZHU/CollectionCode4Java/blob/master/test/org/young/util/ProxyedURLTest.java

 

posted on 2013-07-25 12:47  Memory4Young  阅读(5644)  评论(0编辑  收藏  举报

导航