歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java使用代理訪問網絡的方法

Java使用代理訪問網絡的方法

日期:2017/3/1 9:13:32   编辑:Linux編程

有些時候我們的網絡不能直接連接到外網, 需要使用http或是https或是socket代理來連接到外網,這裡是java使用代理連接到外網的一些方法.

方法一:

使用系統屬性來完成代理設置,這種方法比較簡單, 但是不能對單獨的連接來設置代理:

Properties properties=System.getProperties();

// 設置http訪問要使用的代理服務器的地址

properties.setProperty("http.proxyHost", "192.168.0.254");

// 設置http訪問要使用的代理服務器的端口

properties.setProperty("http.proxyPort", "8080");

// 設置不需要通過代理服務器訪問的主機,可以使用*通配符,多個地址用|分隔

properties.setProperty("http.nonProxyHosts","localhost|192.168.0.*");

// 設置安全訪問使用的代理服務器地址與端口

// 它沒有https.nonProxyHosts屬性,它按照http.nonProxyHosts 中設置的規則訪問

properties.setProperty("https.proxyHost", "192.168.0.254");

properties.setProperty("https.proxyPort", "443");

// 使用ftp代理服務器的主機、端口以及不需要使用ftp代理服務器的主機

properties.setProperty("ftp.proxyHost", "192.168.0.254");

properties.setProperty("ftp.proxyPort", "2121");

properties.setProperty("ftp.nonProxyHosts","localhost|192.168.0.*");

// socks代理服務器的地址與端口

properties.setProperty("socksProxyHost", "192.168.0.254");

properties.setProperty("socksProxyPort", "8000");

// 設置登陸到代理服務器的用戶名和密碼

Authenticator.setDefault(new Authenticator() {

@Override

protected PasswordAuthentication getPasswordAuthentication(){

// TODO Auto-generated method stub

return new PasswordAuthentication(userName,password.toCharArray());

}

});

方法二:使用Proxy來對每個連接實現代理, 這種方法只能在jdk 1.5以上的版本使用(包含jdk1.5),優點是可以單獨的設置每個連接的代理, 缺點是設置比較麻煩:
try {

URLurl = newURL("http://www.linuxidc.com");

//創建代理服務器

InetSocketAddress addr = newInetSocketAddress("192.168.0.254",8080);

Proxyproxy = new Proxy(Proxy.Type.HTTP, addr); // http代理

//如果我們知道代理server的名字,可以直接使用

URLConnection conn =url.openConnection(proxy);

InputStream in =conn.getInputStream();

String s =IOUtils.toString(in);

System.out.println(s);

} catch(Exception e){

e.printStackTrace();

}

}

Copyright © Linux教程網 All Rights Reserved