2015-01-21 70 views
1

如何通过Json发送和获取请求?我试图把值放在Json对象中。
我想完整教程Json
我不是通过Json发送请求到服务器。完整的Json功能在Android中

我想补充key/value对:如果您使用Apache HTTP客户端

jsonObjSend.put("username", "[email protected]"); 
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); 

回答

0

从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();  
    } 
+0

感谢您的帮助 – 2015-01-21 05:36:42

+1

不要忘了接受的答案,如果它的作品! – 2015-01-21 05:39:14

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()); 
      } 
     });