将JSON写入/更新为URL(www.myjson.com)

时间:2018-10-25 05:35:43

标签: java android json

我正在使用www.myjson.com作为我的json文件的存储空间,该文件会经常访问/更新。

我目前将此文件作为在线json文件: https://api.myjson.com/bins/f5fr0

我打算使用android studio频繁地对其进行更新,但是我不知道如何进行更新。如何编写/更新它,以便可以使用android / java代码更改json的值?

1 个答案:

答案 0 :(得分:0)

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpHandler {

   private static final String TAG = HttpHandler.class.getSimpleName();

   public HttpHandler() {
   }

   public String makeServiceCall(String reqUrl) {
      String response = null;
      try {
         URL url = new URL(reqUrl);
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         // read the response
         InputStream in = new BufferedInputStream(conn.getInputStream());
         response = convertStreamToString(in);
      } catch (MalformedURLException e) {
         Log.e(TAG, "MalformedURLException: " + e.getMessage());
      } catch (ProtocolException e) {
         Log.e(TAG, "ProtocolException: " + e.getMessage());
      } catch (IOException e) {
         Log.e(TAG, "IOException: " + e.getMessage());
      } catch (Exception e) {
         Log.e(TAG, "Exception: " + e.getMessage());
      }
      return response;
   }

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

      String line;
      try {
         while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
         }
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         try {
            is.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      return sb.toString();
   }
}

    public class MainActivity extends AppCompatActivity {

   private String TAG = MainActivity.class.getSimpleName();


   ArrayList<HashMap<String, String>> contactList;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);




      new GetJSON().execute();
   }

   private class GetJSON extends AsyncTask<Void, Void, Void> {
      @Override
      protected void onPreExecute() {
         super.onPreExecute();
         Toast.makeText(MainActivity.this,"Json Data is 
            downloading",Toast.LENGTH_LONG).show();

      }

      @Override
      protected Void doInBackground(Void... arg0) {
         HttpHandler sh = new HttpHandler();
         // Making a request to url and getting response
         String url = "https://api.myjson.com/bins/f5fr0";
         String jsonStr = sh.makeServiceCall(url);

         Log.e(TAG, "Response from url: " + jsonStr);
         if (jsonStr != null) {
            try {
               JSONObject jsonObj = new JSONObject(jsonStr);

               // Getting JSON OBJECT node
               JSONArray jsonObjInner = jsonObj.getJSONObject("channel");           


                  String id = jsonObjInner.getString("id");
                  String name = jsonObjInner.getString("name");
                  String description = jsonObjInner.getString("description");                


               }
            } catch (final JSONException e) {
               Log.e(TAG, "Json parsing error: " + e.getMessage());
               runOnUiThread(new Runnable() {
                  @Override
                  public void run() {
                     Toast.makeText(getApplicationContext(),
                     "Json parsing error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
                  }
               });

            }

         } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
               @Override
               public void run() {
                  Toast.makeText(getApplicationContext(), 
                     "Couldn't get json from server. Check LogCat for possible errors!", 
                     Toast.LENGTH_LONG).show();
               }
            });
         }

         return null;
      }

      @Override
      protected void onPostExecute(Void result) {
         super.onPostExecute(result);

      }
   }
}