在android中完成Json功能

时间:2015-01-21 05:22:03

标签: android

如何通过Json发送和获取请求?我正在尝试将值放在Json对象中 我想要完整的Json教程 我不是通过Json向服务器发送请求。

我正在尝试添加key/value对:

jsonObjSend.put("username", "hakimfg@saifsys.com");
jsonObjSend.put("password", "abcxyz");

// 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);

2 个答案:

答案 0 :(得分:0)

如果您使用Apache HTTP Client,从Android发送json对象很容易。这是一个关于如何做的代码示例。您应该为网络活动创建一个新线程,以免锁定UI线程。

 protected void sendJson(final String email, final String pwd) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare(); //For Preparing Message Pool for the child Thread
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObject json = new JSONObject();

                try {
                    HttpPost post = new HttpPost(URL);
                    json.put("email", email);
                    json.put("password", pwd);
                    StringEntity se = new StringEntity( json.toString());  
                    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */
                    if(response!=null){
                        InputStream in = response.getEntity().getContent(); //Get the data in the entity
                    }

                } catch(Exception e) {
                    e.printStackTrace();
                    createDialog("Error", "Cannot Estabilish Connection");
                }

                Looper.loop(); //Loop in the message queue
            }
        };

        t.start();      
    }

答案 1 :(得分:0)

Android提供了几种从Android向服务器发送数据的方法。您可以使用Volley将json发送到任何服务器

<强>段

final String URL = "url";
HashMap<String, String> params = new HashMap<String, String>();
params.put("yourdata", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               //update your UI
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });