Java Apache HttpClient - 代理无响应

时间:2016-03-17 00:00:01

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

我使用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和port示例:

"101.96.11.10":"80"

1 个答案:

答案 0 :(得分:0)

您可以使用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();
}