首页 > 新闻动态 >  

新闻动态
NEWS

Java-HTTP连接时如何应用(一)—— System.Property体式格式

添加时间:2013-7-25 点击量:

在创议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 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


文艺不是炫耀,不是花哨空洞的文字堆砌,不是一张又一张的逆光照片,不是将旅行的意义转化为名牌包和明信片的物质展示;很多时候它甚至完全不美——它嘶吼、扭曲,它会痛苦地抽搐,它常常无言地沉默。——艾小柯《文艺是一种信仰》
分享到: