2016-10-05 5 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());