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

Mri*_*lla 16 java apache-commons-httpclient

我刚刚开始使用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;

}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 46

你可以用EntityUtils#toString()它.

// ...
HttpResponse response = client.execute(get);
String responseAsString = EntityUtils.toString(response.getEntity());
// ...
Run Code Online (Sandbox Code Playgroud)


小智 5

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

BufferedReader br = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent()));
Run Code Online (Sandbox Code Playgroud)

然后阅读它:

String readLine;
String responseBody = "";
while (((readLine = br.readLine()) != null)) {
  responseBody += "\n" + readLine;
}
Run Code Online (Sandbox Code Playgroud)

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

(不要忘记关闭的BufferedReader到底:br.close())