Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract message body out of HttpResponse

Okay, I've successfully connected to a remote server and received a HTTP/1.1 200 OK response and the response is packed into the HttpResponse object. Now how do I get the data in the response out of it, specifically the JSON that was sent from the server?

like image 412
nkcmr Avatar asked Aug 05 '11 04:08

nkcmr


People also ask

How do I get response body from Org Apache Httpresponse?

To get the response body as a string we can use the EntityUtils. toString() method. This method read the content of an HttpEntity object content and return it as a string. The content will be converted using the character set from the entity object.

How do you read a response body in Golang?

To read the body of the response, we need to access its Body property first. We can access the Body property of a response using the ioutil. ReadAll() method. This method returns a body and an error.

How do I get response JSON?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.


2 Answers

something like this: duplicate here : How do I parse JSON from a Java HTTPResponse?

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
like image 190
Bogdan M. Avatar answered Nov 07 '22 13:11

Bogdan M.


Well, you can get the body of the HttpResponse by calling getEntity() which returns an object of type HttpEntity. You will then want to consume the InputStream that is returned from the getContent() method of the HttpEntity. I would do it like this:

public static String entityToString(HttpEntity entity) {
  InputStream is = entity.getContent();
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
  StringBuilder str = new StringBuilder();

  String line = null;
  try {
    while ((line = bufferedReader.readLine()) != null) {
      str.append(line + "\n");
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    try {
      is.close();
    } catch (IOException e) {
      //tough luck...
    }
  }
  return str.toString();
}
like image 39
nicholas.hauschild Avatar answered Nov 07 '22 13:11

nicholas.hauschild