【问题标题】:Java Apache HttpClient - Proxy not respondingJava Apache HttpClient - 代理没有响应
【发布时间】:2016-03-17 00:00:00
【问题描述】:

我在使用 Apache 的 Java HttpClient 的简单程序时遇到问题,其中从代理发送的所有请求都超时 (java.net.ConnectException)。我已经确保列表中的所有代理都能正常工作,所以这不是问题。这是我的代码:

HttpHost proxy = new HttpHost(ip, port, "http"); // the vars ip and port are taken from the function this is in
DefaultHttpClient httpclient = new DefaultHttpClient();
final HttpGet request = new HttpGet(
        "http://www.mysitehere.com"); // And yes, my url works and is not timing out from browser
request.addHeader(
        "User-Agent",
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36");
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
        proxy);
HttpResponse response = httpclient.execute(request); // This code times out.

非常感谢任何帮助,谢谢!

编辑: 示例 ip 和端口:

"101.96.11.10":"80"

【问题讨论】:

    标签: java http httpclient apache-httpclient-4.x


    【解决方案1】:

    您可以使用DynamicProxyRoutePlanner 为每个请求指定代理:

    PoolingHttpClientConnectionManager http
    ...
            this.http = new PoolingHttpClientConnectionManager();
            this.http.setMaxTotal(10);
            this.http.setDefaultMaxPerRoute(10);
            this.http.setValidateAfterInactivity(10000);
    ...
    HttpHost proxy = new HttpHost(ADDRESS, PORT);
    DynamicProxyRoutePlanner routePlanner = new DynamicProxyRoutePlanner(proxy);
    HttpClients.custom()
                    .setConnectionManager(http)
                    .setDefaultRequestConfig(getRequestConfig(timeout))
                    .setRoutePlanner(routePlanner)
                    .setConnectionManagerShared(true)
                    .build();
    ...
    private static RequestConfig getRequestConfig(int timeout) {
        return RequestConfig.copy( RequestConfig.DEFAULT )
        .setConnectTimeout( timeout )
        .setConnectionRequestTimeout( timeout )
        .setSocketTimeout( timeout )
        .setContentCompressionEnabled( true )
        .setRedirectsEnabled( true )
        .setMaxRedirects( 10 )
        .build();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多