set nonProxyHosts in Apache HttpClient 4.1.3

北城以北 提交于 2019-12-05 10:21:31

@moohkooh: here is how i solved the problem.

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);

And then your LinkcheckerProxySelector() would like something like that.

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;
}

So I hope this will help you.

boly38

Just found this answer. The quick way to do that is to set default system planner like oleg told :

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

By default null arg will be set with ProxySelector.getDefault()

Anyway you could define and customize your own. Another example here : EnvBasedProxyRoutePlanner.java (gist)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!