【问题标题】:Why is my HttpClient class freezing with certain URLs为什么我的 HttpClient 类与某些 URL 冻结
【发布时间】:2011-12-06 22:27:05
【问题描述】:

我目前正在掌握新的 HttpClient 库,以提出一个返回 html/css/etc 的基本类。请求的 URL。使用取自here的示例

你可以看下面的例子:

package test;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class Test {

    public final static void main(String[] args) throws Exception {

        HttpClient httpclient = new DefaultHttpClient();
        try {
            HttpGet httpget = new HttpGet("http://www.cwjobs.co.uk/");
            System.out.println("executing request " + httpget.getURI());

            // Create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httpget, responseHandler);

            System.out.println(responseBody);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }
}

我遇到的问题是,如果我将要请求的 URL 设置为 http://www.google.com 之类的东西,那么它会打印出我需要的响应。但是,当我使用诸如 www.cwjobs.co.uk 之类的 URL(仅用作示例)时,它会冻结在执行方法上。

我是 Java 的新手,我了解 HTTP 的基础知识,所以我很想知道: - 虽然我使用了一个基本示例,但我做错了,要么丢失了需要添加才能访问该特定 URL 的内容 - 由于服务器端的环境设置,无法从该特定 URL 获得我想要的响应。 - 任何额外的文献或链接,你可以推荐给我在 Apache.org 网站之外查看

谢谢, 标记

【问题讨论】:

  • 您是否通过代理运行请求以查看是否可以确定发生了什么?
  • 您可能错过了连接超时。谷歌返回快速/小页面。其他站点可能会慢得多或损坏。见http.socket.timeouthc.apache.org/httpclient-3.x/preference-api.html

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


【解决方案1】:

【讨论】:

  • 谢谢。输入 httpclient.getParams().setParameter("http.socket.timeout", new Integer(1000));让它工作!
【解决方案2】:

此代码现已弃用(获取 HttpParams 等)。更好的方法是:

RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

HttpGet httpGet = new HttpGet(url);    
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000).setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
httpGet.setConfig(requestConfig);

【讨论】:

  • 为什么要复制 defaultRequestConfig 而不是直接使用它?
  • 这里是为了说明
  • 好的,谢谢。我认为默认 RequestConfig 不应该设置超时可能是有原因的。
猜你喜欢
  • 2023-01-27
  • 1970-01-01
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 2021-08-31
相关资源
最近更新 更多