I just cant help myself by answering this question.
How can I set nonProxyHosts in the Apache HttpClient 4.1.3?
In the old Httpclient 3.x that was quite simple. U could just set it using the setNonProxyHosts methods.
But now, there's no equivalent method for the new version. I have been looking trough the api docs, tutorials and examples and havent found the solution so far.
to set a normal proxy u can just do it by this:
    HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
Does anybody know if there is an out of the box solution in the new version httpclient 4.1.3 for setting up nonProxyHosts or do I have to do it on my own like
    if (targetHost.equals(nonProxyHost) {
    dont use a proxy
    }
Thanks in advance.
@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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With