Java中使用代理訪問網路的幾種方法__Java

來源:互聯網
上載者:User

      有些時候我們的網路不能直接連接到外網, 需要使用http或是https或是socket代理來串連到外網, 這裡是java使用代理串連到外網的一些方法, 希望對你的程式有用.

 

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

      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"); // 使用ftpProxy 伺服器的主機、連接埠以及不需要使用ftpProxy 伺服器的主機 prop.setProperty("ftp.proxyHost", "192.168.0.254"); prop.setProperty("ftp.proxyPort", "2121"); prop.setProperty("ftp.nonProxyHosts", "localhost|192.168.0.*"); // socksProxy 伺服器的地址與連接埠 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() { returnnew PasswordAuthentication(user, password.toCharArray()); } } 

 

      方法2:使用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(); } } 

 

 

 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.