在 Apache HttpClient 4.1.3 中设置 nonProxyHosts [英] set nonProxyHosts in Apache HttpClient 4.1.3

查看:30
本文介绍了在 Apache HttpClient 4.1.3 中设置 nonProxyHosts的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过回答这个问题来帮助自己.

I just cant help myself by answering this question.

如何在 Apache HttpClient 4.1.3 中设置 nonProxyHosts?

How can I set nonProxyHosts in the Apache HttpClient 4.1.3?

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

In the old Httpclient 3.x that was quite simple. U could just set it using the setNonProxyHosts methods.

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

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

有谁知道新版本httpclient 4.1.3中是否有用于设置nonProxyHosts的开箱即用的解决方案,还是我必须自己做

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
    }

提前致谢.

推荐答案

@moohkooh:这是我解决问题的方法.

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

然后你的 LinkcheckerProxySelector() 会喜欢这样的东西.

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.

这篇关于在 Apache HttpClient 4.1.3 中设置 nonProxyHosts的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆