How to send a JSON object over Request with Android?

236,466

Solution 1

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.

int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);

HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
    postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);

Solution 2

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.

Solution 3

public void postData(String url,JSONObject obj) {
    // Create a new HttpClient and Post Header

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient(myParams );
    String json=obj.toString();

    try {

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

        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se); 

        HttpResponse response = httpclient.execute(httppost);
        String temp = 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.

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

        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();

        //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

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

        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 = 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.

Share:
236,466

Related videos on Youtube

AndroidDev
Author by

AndroidDev

Updated on July 08, 2022

Comments

  • AndroidDev
    AndroidDev almost 2 years

    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.

  • AndroidDev
    AndroidDev almost 14 years
    Hi could it be possible that the server requires me to set a header caled JSON and put the json content in that header ? I sending the url as HttpPost post=new HttpPost("abc.com/xyz/usersgetuserdetails"); But its saying invalid request error. The remiander of the code is the same. Secondly what does json = header = new JSONObject(); Whats happening here
  • AndroidDev
    AndroidDev almost 14 years
    Is postMessage an JSON object ?
  • Primal Pappachan
    Primal Pappachan almost 14 years
    I'm not sure what kind of request is expected by the server. As for this ' json = header = new JSONObject(); ' it's just creating 2 json objects.
  • kubiej21
    kubiej21 about 12 years
    @primpop - Is there any chance that you might be able to provide a simple php script to go along with this? I tried implementing your code, but I for the life of me could not get it to send anything other than NULL.
  • Yekmer Simsek
    Yekmer Simsek almost 12 years
    you can get the output from inputsputstream(in object here) as string like this StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String theString = writer.toString();
  • Karthick
    Karthick over 10 years
    I have post the json object to ASP.Net mvc server. How can I query the same json string in ASP.Net server.?
  • Raptor
    Raptor over 10 years
    postMessage is not defined
  • Lion789
    Lion789 over 10 years
    what is the timeout for?
  • Mayur R. Amipara
    Mayur R. Amipara over 9 years
    what if passing more than one string? like postMessage2.toString().getBytes("UTF8")
  • Esko918
    Esko918 about 9 years
    Do you know the minimum sdk this runs on?
  • Alex
    Alex about 9 years
    I'd be surprised if it had a minimum since it's not GUI. Why not try it out and post your findings.
  • Esko918
    Esko918 about 9 years
    Well i decided to use the native libraries instead. Theres more informatoin about that and since im fairly new to android. Im really a iOS dev. Its better since im reading up on all the docs instead of just plugging and playing with someone elses code. Thanks though
  • tgkprog
    tgkprog over 7 years
    Suggestions to convert a POJO to Json string?
  • Dabbler
    Dabbler almost 7 years
    Upvoted for pointing to okhttp, which is a useful library, but the code as given does not help much. For example, what are the arguments passed to RequestBody.create()? See this link for more details: vogella.com/tutorials/JavaLibrary-OkHttp/article.html
  • CoderBC
    CoderBC almost 7 years
    The accepted answer is depreciated and this approach is better
  • tony gil
    tony gil over 6 years
    currently deprecated, unfortunately. :(