java中使用代理訪問網路的幾種方法
來源:互聯網
上載者:User
http://javasky.bloghome.cn/posts/86087.html 有些時候我們的網路不能直接連接到外網 , 需要使用 http 或是 https 或是 socket 代理來串連到外網 , 這裡是 java 使用代理串連到外網的一些方法 , 希望對你的程式有用 .
方法一 使用系統屬性來完成代理設定 , 這種方法比較簡單 , 但是不能對單獨的串連來設定代理 : /** *
@param args */ /** *
@param args */
public
static
void main(String[] args) { Properties prop = System.getProperties(); // 設定 http 訪問要使用的Proxy 伺服器的地址 prop.setProperty( "http.proxyHost" , "192.168.0.254" ); // 設定 http 訪問要使用的Proxy 伺服器的連接埠 prop.setProperty( "http.proxyPort" , "8080" ); // 設定不需要通過Proxy 伺服器訪問的主機,可以使用 * 萬用字元,多個地址用 | 分隔 prop.setProperty( "http.nonProxyHosts" , "localhost|192.168.0.*" ); // 設定安全訪問使用的Proxy 伺服器地址與連接埠 // 它沒有 https.nonProxyHosts 屬性,它按照 http.nonProxyHosts 中設定的規則訪問 prop.setProperty( "https.proxyHost" , "192.168.0.254" ); prop.setProperty( "https.proxyPort" , "443" ); // 使用 ftp Proxy 伺服器的主機、連接埠以及不需要使用 ftp Proxy 伺服器的主機 prop.setProperty( "ftp.proxyHost" , "192.168.0.254" ); prop.setProperty( "ftp.proxyPort" , "2121" ); prop.setProperty( "ftp.nonProxyHosts" , "localhost|192.168.0.*" ); // socks Proxy 伺服器的地址與連接埠 prop.setProperty( "socksProxyHost" , "192.168.0.254" ); prop.setProperty( "socksProxyPort" , "8000" ); // 設定登陸到Proxy 伺服器的使用者名稱和密碼 Authenticator.setDefault(
new MyAuthenticator( "userName" , "Password" )); }
static
class MyAuthenticator
extends Authenticator {
private String user = "" ;
private String password = "" ;
public MyAuthenticator(String user, String password) {
this . user = user;
this . password = password; }
protected PasswordAuthentication getPasswordAuthentication() {
return
new PasswordAuthentication( user , password .toCharArray()); } } 方法二 使用 Proxy 來對每個串連實現代理 , 這種方法只能在 jdk 1.5 以上的版本使用 ( 包含 jdk1.5), 優點是可以單獨的設定每個串連的代理 , 缺點是設定比較麻煩 :
public
static
void main(String[] args) {
try { URL url =
new URL( "http://www.baidu.com" ); // 建立Proxy 伺服器 InetSocketAddress addr =
new InetSocketAddress( "192.168.0.254" , 8080); // Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr); // Socket 代理 Proxy proxy =
new Proxy(Proxy.Type. HTTP , addr); // http 代理 // 如果我們知道代理 server 的名字 , 可以直接使用 // 結束 URLConnection conn = url.openConnection(proxy); InputStream in = conn.getInputStream(); // InputStream in = url.openStream(); String s = IOUtils.toString(in); System. out .println(s); }
catch (Exception e) { e.printStackTrace(); } } 不是很詳細, 有什麼問題還望大家指正 ================================ /*
* Output:
*
*/
import java.io.InputStream;
import java.net.URL;
public class MainClass {
public static
void main(String args[]) {
try {
URL url =
new URL("http://www.java2s.com");
// Obtain output stream
InputStream is = url.openStream();
// Read and display data from url
byte buffer[] =
new
byte[1024];
int i;
while ((i = is.read(buffer)) != -1) {
System.out.write(buffer, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
} http://www.java2s.com/Code/JavaAPI/java.net/URLopenStream.htm