1 前言
有時候我們的程式中要提供可以使用代理訪問網路,代理的方式包括http、https、ftp、socks代理。比如在IE瀏覽器設定代理。
那我們在我們的java程式中使用代理呢,有如下兩種方式。直接上代碼.
2 採用設定系統屬性
import java.net.Authenticator;import java.net.PasswordAuthentication;import java.util.Properties; public class ProxyDemo1 { public static void main(String[] args) { Properties prop = System.getProperties(); // 設定http訪問要使用的Proxy 伺服器的地址 prop.setProperty("http.proxyHost", "183.45.78.31"); // 設定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", "183.45.78.31"); prop.setProperty("https.proxyPort", "443"); // 使用ftpProxy 伺服器的主機、連接埠以及不需要使用ftpProxy 伺服器的主機 prop.setProperty("ftp.proxyHost", "183.45.78.31"); prop.setProperty("ftp.proxyPort", "21"); prop.setProperty("ftp.nonProxyHosts", "localhost|192.168.0.*"); // socksProxy 伺服器的地址與連接埠 prop.setProperty("socksProxyHost", "183.45.78.31"); prop.setProperty("socksProxyPort", "1080"); // 設定登陸到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()); } } }