2016-10-05 171 views

回答

0

獲取JSON的代碼,這工作正常。

類來獲取JSON

import android.util.Log;   
    import org.apache.http.HttpEntity; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.client.ClientProtocolException; 
    import org.apache.http.client.methods.HttpGet; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.apache.http.util.EntityUtils; 
    import org.json.JSONArray; 
    import org.json.JSONException;   
    import java.io.IOException; 

    public class ApiConnector { //Connector class 
     public JSONArray GetYourJson() 
     { 
      // URL for getting the json 
      String url = "http://api.thingspeak.com/channels/145827/feed/last.json"; 

      // Get HttpResponse Object from url. 
      // Get HttpEntity from Http Response Object 
      HttpEntity httpEntity = null; 

      try 
      { 
       DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient 
       HttpGet httpGet = new HttpGet(url); 

       HttpResponse httpResponse = httpClient.execute(httpGet); 

       httpEntity = httpResponse.getEntity(); 

      } catch (ClientProtocolException e) { 

       // Signals error in http protocol 
       e.printStackTrace(); 

       //Log Errors Here 

      } catch (IOException e) { 
       e.printStackTrace(); 
      } 


      // Convert HttpEntity into JSON Array 
      JSONArray jsonArray = null; 

      if (httpEntity != null) { 
       try { 
        String entityResponse = EntityUtils.toString(httpEntity); 

        Log.e("Entity Response : ", entityResponse); 

        jsonArray = new JSONArray(entityResponse); 

       } catch (JSONException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
      return jsonArray; 
     } 

    } 

AsyckTaks運行ApiConnector,這樣做你的UI不會凍結。

private class GetYourJsonTask extends AsyncTask<ApiConnector,Long,JSONArray> 
    { 
     @Override 
     protected JSONArray doInBackground(ApiConnector... params) { 

      // it is executed on Background thread 

      return params[0].GetYourJson(); 
     } 
     @Override 
     protected void onPostExecute(JSONArray jsonArray) { 
      //TODO: Do what you want with your json here 
     } 
    } 

然後從UI

new GetYourJsonTask().execute(new ApiConnector());