如何使用HttpClient

时间:2011-03-15 23:53:49

标签: java android httpclient

我目前正在尝试使用java中的以下代码通过'uri'获取一些数据:

HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(uri);
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        if(entity != null){
            InputStream stream = entity.getContent();
            callString = stream.toString();
            return callString;
        }

然而这不起作用。有谁知道我在这里做错了什么?

5 个答案:

答案 0 :(得分:1)

你不能像那样打印输入流......而是做这样的事情: -

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet("http://ichart.finance.yahoo.com/table.csv?s=MSFT");
    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        Scanner scanner = new Scanner(entity.getContent());
        while (scanner.hasNextLine()) {
            System.out.println(scanner.nextLine());
        }
    }

打印输出如下: -

1994-02-02,84.75,85.50,84.00,84.00,40924800,2.09
1994-02-01,85.00,85.75,84.50,85.12,44003200,2.12
1994-01-31,85.25,85.87,84.75,85.12,62566400,2.12
1994-01-28,84.50,85.50,84.25,84.87,41875200,2.11
1994-01-27,84.00,84.75,83.25,84.25,51129600,2.10
1994-01-26,85.00,85.00,84.00,84.25,50489600,2.10
1994-01-25,85.25,85.37,84.00,85.12,70361600,2.12
...

答案 1 :(得分:0)

总猜测但不应该是:

String uri = "ichart.finance.yahoo.com/table.csv?s=MSFT"

HttpData data = HttpRequest.get(uri);
System.out.println(data.content);

答案 2 :(得分:0)

您正在尝试下载文件并使用getEntity获取您指定类型的对象。恕我直言这不会工作。

您需要编写实际读取响应流并从中读取内容的代码...

你想做什么?

答案 3 :(得分:0)

如果您知道字符集,要将结果实体读取为字符串使用EntityUtils.toString(HttpEntity)EntityUtils.toString(HttpEntity, String)

答案 4 :(得分:0)

如果您收到NetworkOnMainThreadException,则表示您正在调用client.execute(get);在主线程上,这是一个异常抛出Honeycomb和更高。有关详细信息,请参阅http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html。解决方案是在新线程中运行它。