获取JSON响应Android

时间:2013-03-29 13:55:09

标签: android json

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());
}

我无法获得response。如何在Logger or console. response.toString()response.getEntity.toString()中打印回复不起作用。

我应该将内容类型设置为"application/json"

2 个答案:

答案 0 :(得分:6)

一般方法是:

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

此外,您可以查看响应代码。有时,请求失败。

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

答案 1 :(得分:1)

从响应中获取InputStream,然后使用Scanner来使用其内容。

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

useDelimiter("\\A")表示"分隔符是流的结尾",因此next()会占用所有内容。