JAVA程序通过代理访问网络

指定 Java 程序的代理服务器地址和端口有两种指定方式:

1.通过 命令行参数 指定

如果只需要考虑代理 HTTP 协议请求,只需添加如下命令行参数:

-Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=1080

想要 HTTP 和 HTTPS 协议的请求都通过代理访问网络,可以追加上:

-Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=1080

最终填写的值为:

-Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=1080 -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=1080

2.在程序中使用System.setProperty(String, String)

同样很简单,这里直接上代码:

String proxyHost = "127.0.0.1";
String proxyPort = "1080";

System.setProperty("http.proxyHost", proxyHost);
System.setProperty("http.proxyPort", proxyPort);

// 对https也开启代理
System.setProperty("https.proxyHost", proxyHost);
System.setProperty("https.proxyPort", proxyPort);

推荐使用第一种方案,通过VM Option 的方式,对代码没有任何侵入,绿色环保。

总结

除了上述 http.proxyHost 和 http.proxyPort,以及 https.proxyHost 和 https.proxyPort 在代理时比较有用外,还有一个属性也比较有用,那就是 http.nonProxyHosts,它用来指定哪些主机不使用代理,如果有多个,用英文竖线(|)分隔,可以使用星号 (*)作为通配符。

下表是常用协议对应的代理属性:

协议属性(代理主机/代理端口/不使用代理的主机列表)默认值
HTTPhttp.proxyHost<none>
http.proxyPort80
http.nonProxyHosts<none>
HTTPShttps.proxyHost<none>
https.proxyPort443
https.nonProxyHosts<none>
FTPftp.proxyHost<none>
ftp.proxyPort80
ftp.nonProxyHosts<none>
SOCKSsocksProxyHost<none>
socksProxyPort1080

详细介绍请参考官方说明:Java Networking and Proxies

原文:http://xueliang.org/article/detail/20170116145848852?utm_source=cnblogs.com


已发布

分类

,

来自

标签:

评论

《“JAVA程序通过代理访问网络”》 有 1 条评论

  1. wangzhengzhen

    // http
    System.setProperty(“http.proxySet”, “true”);
    System.setProperty(“http.proxyHost”, “127.0.0.1”);
    System.setProperty(“http.proxyPort”, “8000”);
    System.setProperty(“https.proxySet”, “true”);
    System.setProperty(“https.proxyHost”, “127.0.0.1”);
    System.setProperty(“https.proxyPort”, “8000”);
    // socks
    System.setProperty(“socksProxySet”,”true”);
    System.setProperty(“socksProxyHost”, “127.0.0.1”);
    System.setProperty(“socksProxyPort”, “1080”);

回复 wangzhengzhen 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注