Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;

}
like image 234
Mridang Agarwalla Avatar asked Aug 23 '12 19:08

Mridang Agarwalla


People also ask

How do I get response code from HTTP response?

Use HttpResponse. getStatusLine() , which returns a StatusLine object containing the status code, protocol version and "reason".

How do you read HttpEntity?

To read the content from the entity, you can either retrieve the input stream via the HttpEntity. getContent() method, which returns an InputStream, or you can supply an output stream to the HttpEntity. writeTo(OutputStream) method, which will return once all content has been written to the given stream.

How do I return HttpResponse in Java?

Send Status Code using @ResponseStatus The @ResponseStatus annotation can be used on any method that returns back a response to the client. Thus we can use it on controllers or on exception handler methods.


2 Answers

You can use EntityUtils#toString() for this.

// ...
HttpResponse response = client.execute(get);
String responseAsString = EntityUtils.toString(response.getEntity());
// ...
like image 57
BalusC Avatar answered Oct 08 '22 14:10

BalusC


You need to consume the response body and get the response:

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

And then read it:

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

The responseBody now contains your response as string.

(Don't forget to close the BufferedReader in the end: br.close())

like image 40
Pedro Nunes Avatar answered Oct 08 '22 13:10

Pedro Nunes