LarryDpk
发布于 2021-05-14 / 2231 阅读
0

Java如何设置代理来访问受限资源

1 前言

有些场景我们是需要设置代理才能访问的,如公司内网资源等。Java可以设置代理,让它通过代理来访问资源。

2 三种方法

2.1 通过System.setProperty设置

通过代码设置如下:

System.setProperty("http.proxyHost", "localhost");
System.setProperty("http.proxyPort", "1087");
System.setProperty("https.proxyHost", "localhost");
System.setProperty("https.proxyPort", "1087");

可以设置的属性有:

http.proxyHost
http.proxyPort
https.proxyHost
https.proxyPort
http.nonProxyHosts
socksProxyHost
socksProxyPort

2.2 通过命令行传入

可以通过命令行来传入:

java -Dhttp.proxyHost=localhost -Dhttp.proxyPort=1087 -Dhttps.proxyHost=localhost -Dhttps.proxyPort=1087

在Intellij IDEA设置如下:

2.3 通过Proxy类来设置

示例代码如下:

URL weburl = new URL(URL_STRING);
Proxy webProxy 
  = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 1087));
HttpURLConnection webProxyConnection 
  = (HttpURLConnection) weburl.openConnection(webProxy);

3 总结

代码请查看:https://github.com/LarryDpk/pkslow-samples


参考:Java Connect Via Proxy Server