Skip to content Skip to sidebar Skip to footer

How To Send A Json Object Over Request With Android?

I want to send the following JSON text {'Email':'aaa@tbbb.com','Password':'123456'} to a web service and read the response. I know to how to read JSON. The problem is that the a

Solution 1:

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.

protectedvoidsendJson(final String email, final String pwd) {
        Threadt=newThread() {

            publicvoidrun() {
                Looper.prepare(); //For Preparing Message Pool for the child ThreadHttpClientclient=newDefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
                HttpResponse response;
                JSONObjectjson=newJSONObject();

                try {
                    HttpPostpost=newHttpPost(URL);
                    json.put("email", email);
                    json.put("password", pwd);
                    StringEntityse=newStringEntity( json.toString());  
                    se.setContentType(newBasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                    post.setEntity(se);
                    response = client.execute(post);

                    /*Checking response */if(response!=null){
                        InputStreamin= 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.

Solution 2:

Android doesn't have special code for sending and receiving HTTP, you can use standard Java code. I'd recommend using the Apache HTTP client, which comes with Android. Here's a snippet of code I used to send an HTTP POST.

I don't understand what sending the object in a variable named "jason" has to do with anything. If you're not sure what exactly the server wants, consider writing a test program to send various strings to the server until you know what format it needs to be in.

intTIMEOUT_MILLISEC=10000;  // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.HttpParamshttpParams=newBasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClientclient=newDefaultHttpClient(httpParams);

HttpPostrequest=newHttpPost(serverUrl);
request.setEntity(newByteArrayEntity(
    postMessage.toString().getBytes("UTF8")));
HttpResponseresponse= client.execute(request);

Solution 3:

publicvoidpostData(String url,JSONObject obj) {
    // Create a new HttpClient and Post HeaderHttpParamsmyParams=newBasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClienthttpclient=newDefaultHttpClient(myParams );
    String json=obj.toString();

    try {

        HttpPosthttppost=newHttpPost(url.toString());
        httppost.setHeader("Content-type", "application/json");

        StringEntityse=newStringEntity(obj.toString()); 
        se.setContentEncoding(newBasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se); 

        HttpResponseresponse= httpclient.execute(httppost);
        Stringtemp= EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);


    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
}

Solution 4:

HttpPost is deprecated by Android Api Level 22. So, Use HttpUrlConnection for further.

publicstaticStringmakeRequest(String uri, String json) {
    HttpURLConnection urlConnection;
    String url;
    String data = json;
    String result = null;
    try {
        //Connect 
        urlConnection = (HttpURLConnection) ((newURL(uri).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

        //WriteOutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = newBufferedWriter(newOutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();

        //ReadBufferedReader bufferedReader = newBufferedReader(newInputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = newStringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

Solution 5:

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 = newAsyncHttpClient();
client.get("http://www.google.com", newAsyncHttpResponseHandler() {
    @OverridepublicvoidonSuccess(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.

Post a Comment for "How To Send A Json Object Over Request With Android?"