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

Mridang Agarwalla picture Mridang Agarwalla · Aug 23, 2012 · Viewed 40.6k times · Source

I've just begun using Apache's HTTP Client library and noticed that there wasn't a built-in method of getting the HTTP response as a String. I'm just looking to get it as as String so that i can pass it to whatever parsing library I'm using.

What's the recommended way of getting the HTTP response as a String? Here's my code to make the request:

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;

}

Answer

BalusC picture BalusC · Aug 23, 2012

You can use EntityUtils#toString() for this.

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