有时候使用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
  
原文:http://noteworthy.blog.51cto.com/7695617/1615176