How to send a JSON object over Request with Android?

AndroidDev picture AndroidDev · Jun 12, 2010 · Viewed 234k times · Source

I want to send the following JSON text

{"Email":"[email protected]","Password":"123456"}

to a web service and read the response. I know to how to read JSON. The problem is that the above JSON object must be sent in a variable name jason.

How can I do this from android? What are the steps such as creating request object, setting content headers, etc.

Answer

Primal Pappachan picture Primal Pappachan · Jun 12, 2010

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.