使用Apache的HTTP客户端,获取HTTP响应作为字符串的推荐方法是什么?

17

我刚开始使用Apache的HTTP Client库,并注意到它没有内置方法将HTTP响应作为字符串获取。我只想将其作为字符串获取,以便将其传递给任何解析库。

获取HTTP响应作为字符串的推荐方法是什么?以下是我用于发出请求的代码:

public String doGet(String strUrl, List<NameValuePair> lstParams) {

    String strResponse = null;

    try {

        HttpGet htpGet = new HttpGet(strUrl);
        htpGet.setEntity(new UrlEncodedFormEntity(lstParams));

        DefaultHttpClient dhcClient = new DefaultHttpClient();

        PersistentCookieStore pscStore = new PersistentCookieStore(this);
        dhcClient.setCookieStore(pscStore);

        HttpResponse resResponse = dhcClient.execute(htpGet);
        //strResponse = getResponse(resResponse);

    } catch (ClientProtocolException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }

    return strResponse;

}
4个回答

51
您可以使用 EntityUtils#toString() 来实现此操作。
// ...
HttpResponse response = client.execute(get);
String responseAsString = EntityUtils.toString(response.getEntity());
// ...

1
这个答案是使用HttpClient的正确方式。在我看来,Apache Jersey比HttpClient更容易使用。 - Paul Sanwald
1
@Paul:我不确定你所说的“Apache Jersey”是什么意思。在Apache项目中并没有这样的东西。"Jersey"是Sun/Oracle JAX-RS API的参考实现,根本不是HTTP客户端。 - BalusC
1
抱歉,我指的是Sun/Oracle的Jersey。它包含一个具有更流畅API的HTTP客户端。 - Paul Sanwald

5

您需要获取响应体并获得响应:

BufferedReader br = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent()));

然后阅读它:

String readLine;
String responseBody = "";
while (((readLine = br.readLine()) != null)) {
  responseBody += "\n" + readLine;
}

responseBody现在包含了您的响应字符串。

(不要忘记最后关闭BufferedReader:br.close()


1
你可以这样做:
Reader in = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

使用读取器,您可以构建字符串。但是,如果您使用SAX,则可以直接将流传递给解析器。这样,您就不必创建字符串,内存占用也会更低。

0

就代码的简洁性而言,可以像这样使用Fluent API

import org.apache.http.client.fluent.Request;
[...]
String result = Request.Get(uri).execute().returnContent().asString();

文档警告说,从内存消耗的角度来看,这种方法并不理想。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接