在Apache HttpClient 4.1.3中设置nonProxyHosts

Joo*_*ols 5 proxy apache-httpclient-4.x

我回答这个问题时无法帮助自己.

如何在Apache HttpClient 4.1.3中设置nonProxyHosts?

在旧的Httpclient 3.x中,这非常简单.你可以使用setNonProxyHosts方法设置它.

但是现在,新版本没有等效的方法.我一直在寻找api文档,教程和示例,到目前为止尚未找到解决方案.

设置正常的代理你可以这样做:

    HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
Run Code Online (Sandbox Code Playgroud)

有没有人知道新版本httpclient 4.1.3中是否有开箱即用的解决方案来设置nonProxyHosts或者我必须自己做

    if (targetHost.equals(nonProxyHost) {
    dont use a proxy
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Joo*_*ols 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);
Run Code Online (Sandbox Code Playgroud)

然后你的 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;
}
Run Code Online (Sandbox Code Playgroud)

所以我希望这会对你有所帮助。