How to send a JSON object over Request with Android?

前端 未结 8 2062
慢半拍i
慢半拍i 2020-11-22 03:32

I want to send the following JSON text

{\"Email\":\"aaa@tbbb.com\",\"Password\":\"123456\"}

to a web service and read the response. I kno

8条回答
  •  梦谈多话
    2020-11-22 03:55

    Sending a json object from Android is easy if you use Apache HTTP Client. Here's a code sample on how to do it. You should create a new thread for network activities so as not to lock up the UI thread.

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

    You could also use Google Gson to send and retrieve JSON.

提交回复
热议问题