2013-09-28 49 views
0

下面的代碼來解析可以通過下面的代碼我不能夠從URL使用JSON數據。無法與Android中

try{ 

    HttpClient client= new DefaultHttpClient(); 

      HttpGet http= new HttpGet("http://api.androidhive.info/contacts/"); 

      HttpResponse response = client.execute(http); 

      HttpEntity httpentity = response.getEntity(); 

      is= httpentity.getContent(); 

     }catch (ClientProtocolException e) { 

      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

回答

0

做這樣..這是getiing使用在許多應用從URL的JSON響應我的工作代碼。

/** 
* This method used to get json from url. 
* 
* @param url 
*   represented url 
* @return represented {@link JSONObject} 
*/ 
public JSONObject getJSONFromUrl(String url) { 

    InputStream is = null; 
    JSONObject jObj = null; 
    try { 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 
     HttpResponse httpResponse = httpClient.execute(httpGet); 

     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    try { 
     jObj = new JSONObject(getResponseBody(is)); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return jObj; 
} 

/** 
* This method used to get response body. 
* 
* @param instream 
*   represented input stream 
* @return represented {@link String} 
* @throws IOException 
*    represented {@link IOException} 
* @throws ParseException 
*    represented {@link ParseException} 
*/ 
public String getResponseBody(final InputStream instream) throws IOException, ParseException { 

    if (instream == null) { 
     return ""; 
    } 

    StringBuilder buffer = new StringBuilder(); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "utf-8")); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      buffer.append(line); 
     } 

    } finally { 
     instream.close(); 
     reader.close(); 
    } 
    System.out.println(buffer.toString()); 
    return buffer.toString(); 

} 
1

如果你試圖檢索數據,那麼你可以使用下面的代碼,其將該響應轉換爲字符串值,

HttpClient client= new DefaultHttpClient(); 
HttpPost http=new HttpPost("http://api.androidhive.info/contacts/"); 
HttpResponse response = client.execute(http); 
HttpEntity httpentity = response.getEntity(); 
String result=EntityUtils.toString(httpentity); 

使用此結果解析JSON值。您可以使用org.json jar文件,其中包含的構造函數JSONArray字符串作爲參數。

例如, JSON解析

JSONArray jarray=new JSONArray(result); 
for(int i=0;i<jarray.length();i++) 
{ 
    JSONObject jobject=jarray.getJSONObject(i); 
    System.out.println(jobject.getString("test")); 
} 

在你的情況下,你需要解析第一個JSONObject而不是JSONArray。