有時候使用Java需要設置代理,那麼如何實現呢?
使用System.setProperty(...)
http.proxyHost (default: <none>) http.proxyPort (default: 80 if http.proxyHost specified)
使用jvmargs
# 在啓動時指定相應的property java -Dhttp.proxyHost=your_proxy_host -Dhttp.proxyPort=proxy_port_number ... # selenium還支持指定username和password,純java中支持嗎? java -Dhttp.proxyHost=myproxy.com -Dhttp.proxyPort=1234 -Dhttp.proxyUser=username -Dhttp.proxyPassword=example -jar selenium-server.jar
使用系統默認的代理
System.setProperty("java.net.useSystemProxies", "true");
使用Proxy類設定參數
// 創建Proxy實例 proxy IP地址=127.0.0.1 端口=8087 Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8087)); URL url = new URL("http://www.google.com"); HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy); uc.connect();
【注】訪問某個資源不使用代理,如何設置?
// 對某個資源不使用代理 URL url = new URL("http://internal.server.local/"); URLConnection conn = url.openConnection(Proxy.NO_PROXY);
# 也可以使用http.nonProxyHosts (default: <none>) http.nonProxyHosts indicates the hosts which should be connected too directly and not through the proxy server. The value can be a list of hosts, each seperated by a |, and in addition a wildcard character (*) can be used for matching. For example: -Dhttp.nonProxyHosts="*.foo.com|localhost".
使用第三方包如Apache的HttpClient包
DefaultHttpClient httpclient = new DefaultHttpClient(); HttpHost proxy = new HttpHost("someproxy", 8080); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
【疑】ProxySelector到底是個什麼鬼??
根據不同的URL來決定選取哪個proxy來訪問資源(譬如,http的用127.0.0.1:8080訪問;ftp的用127.0.0.1:3128訪問等等)
public void foo() throws URISyntaxException { // 開啓系統默認代理 //(因爲這裏使用了系統代理設置來說明ProxySelector是如何根據不同的URL來選取Proxy的) System.setProperty("java.net.useSystemProxies", "true"); ProxySelector ps = ProxySelector.getDefault(); List<Proxy> lst = null; for (URI uri : new URI[]{new URI("ftp://ftpsite.com"), new URI("http://httpsite.com"), new URI("https://httpssite.com")}) { lst = ps.select(uri); System.out.println(lst); } }
執行結果(下圖):
更詳細的說明(如需要username和password驗證的)
參考:
http://www.rgagnon.com/javadetails/java-0085.html
http://docs.oracle.com/javase/6/docs/technotes/guides/net/properties.html