Kevin
Kevin

Reputation: 23634

Getting JSON response Android

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);

try {
    StringEntity documentStringified = new StringEntity(Obj.toString());
    httpPost.setEntity(documentStringified);
} catch (UnsupportedEncodingException e) {
    Log.d("UnsupportedEncodingException", e.toString());
}

try {
    HttpResponse response = httpClient.execute(httpPost);
    Log.d("Response", response.toString());
} catch (IOException e) {
    Log.d("IOException", e.toString());
}

I am not able to get the response. How to print the response in Logger or console. response.toString() or response.getEntity.toString() does not work.

Should i set the Content-type as "application/json".

Upvotes: 1

Views: 4524

Answers (2)

Ostap Andrusiv
Ostap Andrusiv

Reputation: 4907

The general approach is:

String result = EntityUtils.toString(response.getEntity());  

Moreover, you can check response code. Sometimes, requests fail.

int status = response.getStatusLine().getStatusCode();
if (status == 200) {
    String result = EntityUtils.toString(response.getEntity());    
}

Upvotes: 6

salezica
salezica

Reputation: 77109

Get the InputStream out of the response, and then use a Scanner to consume its contents.

String responseContent = new Scanner(inputStream).useDelimiter("\\A").next();

useDelimiter("\\A") means "the delimiter is the end of the stream", so next() consumes all of the content.

Upvotes: 1

Related Questions