0

我正在尝试使用 Apache HtppClient 执行 HTTP GET 并读取响应。我目前的努力看起来像这样

    def listAlertsUrl = "http://example.com/whatever"
    HttpGet listAlertsRequest = new HttpGet(listAlertsUrl)
    HttpResponse response = httpClient.execute(listAlertsRequest)
    HttpEntity entity = response.entity
    EntityUtils.consume(entity)

    // newReader() is a method that Groovy adds to InputStream
    Reader jsonResponse = entity.content.newReader()

    try {
        // do stuff with the Reader
    } finally {
        jsonResponse.close()
    }

但是,当我尝试使用时Reader出现错误:

原因:java.io.IOException:尝试从关闭的流中读取。

我正在努力寻找如何使用 HttpClient v.4 的示例,因为我的 Google 搜索只返回具有完全不同 API 的旧版本的示例。

4

3 回答 3

1

如评论和另一个答案中所述,删除该EntityUtils.consume(entity)行。newReader另外,我建议不要使用该方法withReader(它会自动处理关闭流)。我还建议在创建阅读器时指定编码

def listAlertsUrl = 'http://example.com/whatever'
HttpGet listAlertsRequest = new HttpGet(listAlertsUrl)
HttpResponse response = httpClient.execute(listAlertsRequest)
HttpEntity entity = response.entity
// specify the encoding of HTTP response instead of using default JVM encoding
entity.content.withReader(entity.contentEncoding.value) { jsonResponse ->
    // do stuff with the Reader
}
于 2013-05-29T12:51:39.750 回答
0

你可以这样做:

String getUrl() throws IOException{
    HttpClient client = new DefaultHttpClient();
    HttpGet listAlertsRequest = new HttpGet("http://www.google.com");
    HttpResponse response =client.execute(listAlertsRequest);

    String resultBody = EntityUtils.toString(response.getEntity());
    EntityUtils.consume(response.getEntity());
    return resultBody;
}
于 2013-05-29T09:16:01.940 回答
0

consume()

确保实体内容被完全使用并且内容流(如果存在)被关闭。

您正在尝试从关闭的流中读取

于 2013-05-29T08:48:06.257 回答