繁体   English   中英

在使用Apache的HTTP客户端时,将HTTP响应作为字符串的建议方法是什么?

[英]What's the recommended way to get the HTTP response as a String when using Apache's HTTP Client?

我刚刚开始使用Apache的HTTP客户端库,并注意到没有内置的方法将HTTP响应作为String获取。 我只是想像String那样得到它,以便我可以将它传递给我正在使用的任何解析库。

将HTTP响应作为String获取的推荐方法是什么? 这是我提出请求的代码:

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;

}

您可以使用EntityUtils#toString()

// ...
HttpResponse response = client.execute(get);
String responseAsString = EntityUtils.toString(response.getEntity());
// ...

您需要使用响应主体并获得响应:

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()

你可以这样做:

Reader in = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

使用阅读器,您将能够构建您的字符串。 但是如果您使用的是SAX,则可以直接将流提供给解析器。 这样您就不必创建字符串,内存占用也会降低。

在代码的简洁性方面,它可能正在使用Fluent API,如下所示:

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

该文档警告说,这种方法在内存消耗方面并不理想。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM