2011-07-06 392 views

回答

0
HttpClient httpclient = new DefaultHttpClient(); 
    // Prepare a request object 
    HttpGet httpget = new HttpGet(url); 
    // Execute the request 
    HttpResponse response; 

    JSONArray arr = new JSONArray(); 
    try { 
     response = httpclient.execute(httpget); 

     HttpEntity entity = response.getEntity(); 

     if (entity != null && response.getStatusLine().getStatusCode() == 200) { 
       // A Simple JSON Response Read 
       InputStream instream = entity.getContent(); 
       String result = convertStreamToString(instream); 
       arr=new JSONArray(result); 
       instream.close(); 

      } 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      Log.e(TAG,e.toString()); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      Log.e(TAG,e.toString()); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      Log.e(TAG,e.toString()); 
     } 

     return arr; 


public static String convertStreamToString(InputStream is) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     Log.e(TAG + "ERROR",e.toString()); 

    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      Log.e(TAG + "ERRO",e.toString()); 
     } 
    } 
    return sb.toString(); 
} 

至於用於解析,在這裏你去:http://developer.android.com/reference/org/json/package-summary.html

順便說一句,這是所有容易在谷歌發現:)

+0

不知道它是那麼容易在Java解析JSON:o –

+0

此運行在14 sdk版本?如果要在2.3.3上運行,我該怎麼辦?而不是JSON獲得這些參數的替代方法? –

+0

這段代碼在android studio的TAG中拋出錯誤。 ''TAG'在'android.support.v4.app.Fragment'中有專用權限'' – Shivam