在android中使用json发送请求

时间:2011-02-28 12:55:31

标签: android image json imageview

  

可能重复:
  send requst from json to java server in android

现在我在画廊项目工作。所有图像都将在服务器数据库上。使用json我想发送请求并从服务器获取响应,在服务器端我们使用java。当数据库中的图像发生变化时,图库图像也必须动态更改。如何使用json这个目的,请帮帮我

1 个答案:

答案 0 :(得分:-1)

package com.devstream.http;  
    import org.json.JSONException;
    import org.json.JSONObject;
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;

    public class MainActivity extends Activity {
     private static final String TAG = "MainActivity";
     private static final String URL = "http://www.yourdomain.com:80";

     @Override   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      // JSON object to hold the information, which is sent to the server
      JSONObject jsonObjSend = new JSONObject();

      try {
       // Add key/value pairs
       jsonObjSend.put("key_1", "value_1");
       jsonObjSend.put("key_2", "value_2");

       // Add a nested JSONObject (e.g. for header information)
       JSONObject header = new JSONObject();
       header.put("deviceType","Android"); // Device type
       header.put("deviceVersion","2.0"); // Device OS version
       header.put("language", "es-es"); // Language of the Android client
       jsonObjSend.put("header", header);

       // Output the JSON object we're sending to Logcat:
       Log.i(TAG, jsonObjSend.toString(2));

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

      // Send the HttpPostRequest and receive a JSONObject in return
      JSONObject jsonObjRecv = HttpClient.SendHttpPost(URL, jsonObjSend);

      /*
       *  From here on do whatever you want with your JSONObject, e.g.
       *  1) Get the value for a key: jsonObjRecv.get("key");
       *  2) Get a nested JSONObject: jsonObjRecv.getJSONObject("key")
       *  3) Get a nested JSONArray: jsonObjRecv.getJSONArray("key")
       */


     }
    }