嗨,我如何配置Apache HttpClient绕过本地地址的代理?

时间:2014-02-04 16:14:24

标签: proxy apache-httpclient-4.x

我正在配置客户端:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpHost proxy = new HttpHost(proxyHost, proxyPort, "http");
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

现在,我想告诉我的客户不要使用代理“localhost”或127.0.0.1。

谢谢!

1 个答案:

答案 0 :(得分:11)

使用HttpClient 4.3 API

HttpHost proxy = new HttpHost("someproxy", 8080);
HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy) {

    @Override
    public HttpRoute determineRoute(
            final HttpHost host,
            final HttpRequest request,
            final HttpContext context) throws HttpException {
        String hostname = host.getHostName();
        if (hostname.equals("127.0.0.1") || hostname.equalsIgnoreCase("localhost")) {
            // Return direct route
            return new HttpRoute(host);
        }
        return super.determineRoute(host, request, context);
    }
};
CloseableHttpClient client = HttpClients.custom()
        .setRoutePlanner(routePlanner)
        .build();