Java使用代理Proxy訪問網絡及其驗證


在Java的網絡編程中,有時候內網服務器需要訪問外網的網絡資源,這時候就需要使用代理。

設置代理(Proxy)可以有兩種方式:

1.通過設置系統屬性(System.setPropery(String key, String value)的方式

可以使用其中的http.proxyHost,http.proxyPort這兩個屬性,分別設置代理服務器地址和代理端口。

//在你發起Http請求之前設置一下屬性 
System.setProperty("http.proxyHost", "www.proxy.com"); 
System.setProperty("http.proxyPort", "8080"); 

  

替換上面的代理服務器地址或IP地址,以及相應的端口為真實端口,Http連接就可以工作了。需要注意的是如果你設置了這些屬性,那么所有的Http請求都會通過代理服務器。

這些屬性是JVM級別的,設置了以后對所有的同類請求都有效。

如果你的代理服務器不需要驗證,那到此就結束了。但一般都是需要驗證的。但是你要是看了上面Java支持的屬性列表,你就會發現那里面並沒有期望中的

http.proxyUserName=username 
http.proxyPassword=password 

  


這兩個屬性。 這時就需要java.net.Authenticator類來完成一般的Http驗證。

但是java.net.Authenticator這個類卻是個抽象類,我們要使用還需要實例化一下子自己的類。如下

public class BasicAuthenticator extends Authenticator { 
String userName; 
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()); 
} 
} 

 

我們需要覆蓋java.net.Authenticator類的getPasswordAuthentication()方法,並返回一個PasswordAuthentication實例。要使他起作用,還需要設置


Authenticator.setDefault(new BasicAuthenticator(userName, password));

這樣就提供了基於Http Basic的驗證,接着就可以順暢的使用需要驗證的代理了。

2.通過java.net.Proxy類

這種方式是實例化一個Proxy類提供代理服務器的信息,如端口和地址。

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
URLConnection conn = url.openConnection(proxy);

使用代理的方式是在打開Http連接的時候同時傳遞一個Proxy參數。如果需要驗證信息的話我們可以添加一個Http頭參數來實現。

//格式如下: 
"Proxy-Authorization"= "Basic Base64.encode(user:password)" 
String headerKey = "Proxy-Authorization"; 
String headerValue = "Basic " + Base64.encode(user+":"+password); 
conn.setRequestProperty(headerKey, headerValue); 

//.......... 

  


其中的Base64.encode(user:password)是指把用戶名和密碼用冒號連接起來之后使用Base64編碼后的值作為值的一部分。

通過這種方式只影響特定的Http連接,但是需要對代碼進行修改。這種方式下是否可以使用Authenticator還未做驗證。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM