java中如何設定代理

來源:互聯網
上載者:User

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());        }    }     }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.