【问题标题】:Simple java HttpClient program not working简单的 java HttpClient 程序不起作用
【发布时间】:2012-06-25 20:06:25
【问题描述】:

我有 HttpClient 4.1。请看以下程序:

import org.apache.http.client.methods.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

public class SysCommands {
    public static void main(String [] args){
        try{
            HttpClient c = new DefaultHttpClient();
            System.out.println("Initial part");
            HttpGet method = new HttpGet("http://www.google.com");
            HttpResponse resp = c.execute(method);
            System.out.println("Method executed");
            String s = "";
            resp.getHeaders(s);
            System.out.println("headers are "+s);
            BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                    System.out.println(line);
            }
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

当我运行它时,我得到org.apache.http.client.ClientProtocolException。有什么问题?

【问题讨论】:

  • 它到底在哪里抛出异常?你的代码对我有用。另外,运行时/进程代码与您的问题有什么关系,如果不是,请删除。
  • 尝试使用 e.printStackTrace() 而不是 System.out.println(e) 来获取完整的堆栈跟踪。此外,您的 reps.getHeaders(s) 返回一个数组, s 没有改变。
  • 在执行之后。它仅适用于 google.com。我试过 www.affinity.com,它奏效了。怎么会!!
  • 与此无关,我强烈推荐 String string = EntityUtils.toString(resp.getEntity()); 之类的东西,而不是滚动你自己的 BufferedReader/InputStreamReader/loop 东西。
  • 我做到了,但同样的事情发生了。在 google.com 上这样做会给我错误。谷歌会以某种方式避免此类调用吗?

标签: java apache-httpclient-4.x


【解决方案1】:

可能是 google 将您重定向到您的“本地”google 站点。我住在荷兰,当我访问 www.google.com 时,它会响应 HTTP 302 重定向到 www.google.nl。

我不确定默认的 http 客户端是如何配置的,但它可能默认不遵循重定向。

【讨论】:

    【解决方案2】:

    您是否考虑过使用 HttpURLConnection 代替 HttpClient?

    【讨论】:

    • 我只是尝试了一些不同的网站,它工作。然而 google.com 没有。我不知道 HttpURLConnection。在大多数示例中,都使用了 HttpClient,所以我尝试了一下。我会看看。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2012-05-15
    相关资源
    最近更新 更多