如何接收json响应

时间:2012-06-25 17:29:25

标签: java android json http

我需要将响应转换为字符串..

        HttpClient httpclient = new DefaultHttpClient();  
        Log.d("HTTP","Exe");
        String url=Sign(token);
        Log.d("HTTP","Exe");

        HttpPost httpPost;
        httpPost = new HttpPost(url);

响应(json)应该是

{
    "url": "http://db.tt/APqhX1",
    "expires": "Tue, 01 Jan 2030 00:00:00 +0000"
}

我如何收到它?我正在使用Android(java)..

2 个答案:

答案 0 :(得分:2)

这是将任何json作为http响应的方法。我希望它会有用。

HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();

try {
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 256);
 StringBuilder sb = new StringBuilder();
 String line = null;
 while ((line = reader.readLine()) != null)  sb.append(line); 
     result = sb.toString();
 is.close();
} catch (Exception e) {}

 JSONArray jArray = new JSONArray(result);
 for(int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
String url= json_data.getString("url");
    String expires= json_data.getString("expires");
 }

答案 1 :(得分:0)

有很多例子,如果你谷歌并尝试反正:

      response = client.execute(httpPost);
  HttpEntity httpEntity = response.getEntity();
  InputStream is = httpEntity.getContent();

..将Inputstream转换为字符串