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?
Asked
Active
Viewed 2.0k times
14

nkcmr
- 10,690
- 25
- 63
- 84
4 Answers
25
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);
4
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();
}

nicholas.hauschild
- 42,483
- 9
- 127
- 120
1
You may also use EntityUtils
response = cl.execute(p); //cl is http client and p is the post request
if(response.getStatusLine().getStatusCode()==200)
{
try
{
String resp_body = EntityUtils.toString(response.getEntity());
Log.v("resp_body", resp_body.toString());
JSONObject jsobj = new JSONObject(resp_body);
}
catch(Exception e)
{
Log.e("sometag",e.getMessage());
}
}
PS : You may have to do this in a separate thread, other than the main thread, like in the doInBackground() of an AsyncTask or Network operation on main thread exception may occur.

Sachin Murali G
- 575
- 6
- 25
0
Use a BasicResponseHandler when calling httpclient.execute()
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
String response = httpclient.execute(httpget, resonseHandler);

HimalayanCoder
- 9,630
- 6
- 59
- 60