How to send a JSON object over Request with Android?

前端 未结 8 1855
慢半拍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.

    0 讨论(0)
  • There's a surprisingly nice library for Android HTTP available at the link below:

    http://loopj.com/android-async-http/

    Simple requests are very easy:

    AsyncHttpClient client = new AsyncHttpClient();
    client.get("http://www.google.com", new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(String response) {
            System.out.println(response);
        }
    });
    

    To send JSON (credit to `voidberg' at https://github.com/loopj/android-async-http/issues/125):

    // params is a JSONObject
    StringEntity se = null;
    try {
        se = new StringEntity(params.toString());
    } catch (UnsupportedEncodingException e) {
        // handle exceptions properly!
    }
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    
    client.post(null, "www.example.com/objects", se, "application/json", responseHandler);
    

    It's all asynchronous, works well with Android and safe to call from your UI thread. The responseHandler will run on the same thread you created it from (typically, your UI thread). It even has a built-in resonseHandler for JSON, but I prefer to use google gson.

    0 讨论(0)
提交回复
热议问题