2012-04-24 25 views
5

我只是不能帮助回答这个问题。在Apache HttpClient 4.1.3中设置nonProxyHosts

如何在Apache HttpClient 4.1.3中设置nonProxyHosts?

在旧的Httpclient 3.x中很简单。你可以使用setNonProxyHosts方法来设置它。

但是现在,没有用于新版本的等效方法。我一直在浏览api文档,教程和示例,并没有找到解决方案。

设置一个正常的代理U可以只凭这做:

HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); 
    DefaultHttpClient httpclient = new DefaultHttpClient(); 
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 

有谁知道是否有设立nonProxyHosts或做一个彻头彻尾的新版本4.1.3的HttpClient盒解决方案我必须这样做我自己喜欢

if (targetHost.equals(nonProxyHost) { 
    dont use a proxy 
    } 

在此先感谢。

+0

我可以通过使用proxyselector来解决这个问题。 – Jools 2012-04-25 09:08:50

+0

可否请您提交您的解决方案,我遇到同样的问题。 – moohkooh 2013-02-07 19:06:09

回答

3

@moohkooh:这是我如何解决问题。

DefaultHttpClient client = new DefaultHttpClient(); 

//use same proxy as set in the system properties by setting up a routeplan 
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(), 
    new LinkCheckerProxySelector()); 
client.setRoutePlanner(routePlanner); 

然后你的LinkcheckerProxySelector()会喜欢那样的东西。

private class LinkCheckerProxySelector extends ProxySelector { 

@Override 
public List<Proxy> select(final URI uri) { 

    List<Proxy> proxyList = new ArrayList<Proxy>(); 

    InetAddress addr = null; 
    try { 
    addr = InetAddress.getByName(uri.getHost()); 
    } catch (UnknownHostException e) { 
    throw new HostNotFoundWrappedException(e); 
    } 
    byte[] ipAddr = addr.getAddress(); 

    // Convert to dot representation 
    String ipAddrStr = ""; 
    for (int i = 0; i < ipAddr.length; i++) { 
    if (i > 0) { 
     ipAddrStr += "."; 
    } 
    ipAddrStr += ipAddr[i] & 0xFF; 
    } 

//only select a proxy, if URI starts with 10.* 
    if (!ipAddrStr.startsWith("10.")) { 
    return ProxySelector.getDefault().select(uri); 
    } else { 
    proxyList.add(Proxy.NO_PROXY); 
    } 
    return proxyList; 
} 

所以我希望这会帮助你。

+0

自4.0'不推荐使用'ProxySelectorRoutePlanner'; doc告诉使用'SystemDefaultRoutePlanner'。无论如何,我会建议一种基于环境的新方法 – boly38 2015-09-18 13:23:47

1

刚刚发现this answer。快速的方法来做到这一点是要设置默认系统规划者像奥列格说:

HttpClientBuilder getClientBuilder() { 
    HttpClientBuilder clientBuilder = HttpClientBuilder.create(); 
    SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(null); 
    clientBuilder.setRoutePlanner(routePlanner); 
    return clientBuilder; 
} 

默认null阿根廷将与ProxySelector.getDefault()

反正你可以定义和定制自己的设置。另一个例子在这里:EnvBasedProxyRoutePlanner.java (gist)

相关问题