Friday, October 28, 2011

Step 7 : POST data from JSON Android Client to WCF REST WebService

POST JSON data from an Android Client to a WCF RESTful WebService

The full source code is on Google Code :

The full Eclipse Indigo 3.7 - Android  project zipped on Google Docs :

All files of the WCF RESTful Web Service are also on Google Code :

The full Visual Web Developer project -  VWD  Express 2010 also on Google Docs :

First we tried to post XML formatted data to a WCF Web Service with FIDDLER ( step 5 ) :

Then tried to post JSON data to a WCF Web Service with FIDDLER ( step 6 ) :

Now , knowing that the WCF Web Service responds OK with both XML and JSON ,
we can take our simple sample project to the ANDROID Client Test :

package net.learn2develop.AndroidViews;

import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
// import org.json.JSONObject;
import org.json.JSONStringer;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class SavePerson extends Activity {

private final static String SERVICE_URI = "";

   public void onCreate(Bundle savedInstanceState) {

       // String plate = new String("test");
       // POST request to
            HttpPost request = new HttpPost(SERVICE_URI + "/json/adduser");
            request.setHeader("Accept", "application/json");
            request.setHeader("Content-type", "application/json");
            String not = new String(" ");
            try {
            // Build JSON string
            JSONStringer vehicle = new JSONStringer()
            StringEntity entity = new StringEntity(vehicle.toString());
            Toast.makeText(this, vehicle.toString() + "\n", Toast.LENGTH_LONG).show() ;
            // Send request to WCF service
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response = httpClient.execute(request);
            // Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());
            Toast.makeText(this, response.getStatusLine().getStatusCode() + "\n", Toast.LENGTH_LONG).show() ;
            }catch (Exception e) {
            not = "NOT ";
            Toast.makeText(this, not + " OK ! " + "\n", Toast.LENGTH_LONG).show() ;


        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "json/adduser")]
        PersonData AddJsonUser(RequestData rData);

In our simple example we create a JSONStringer object with "rData" key and "details" sub-key ;
      "rData" is the variable of the function "AddJsonUser" ;
"details" is the single property of the object "RequestData" :

    [DataContract(Namespace = "")]
    public class RequestData
        public string details { get; set; }

The string  "bar|bob||why" of the JSONStringer is hard-coded to simplify things ;
After being parsed - it ends up in the SQLS table "Users" :
AddUser is the function triggered by the POST WCF Webservice
with a JSON request body -  JSONStringer vehicle : 

        public PersonData AddUser(RequestData rData)
            bool returnBool = false;

            var data = rData.details.Split('|');
            var response = new PersonData
                Name = data[0],
                User = data[1],
                Email = data[2],
                Password = data[3]

            SqlConnection dbConn = new SqlConnection(connStr);
            string sqlStr = "INSERT INTO users(username,name,email,password)
                          values('" + data[0] + "', '" + data[1] + "', '" + data[2] + "', '" + data[3] + "');";
            SqlCommand dbCommand = new SqlCommand(sqlStr, dbConn);
                if (dbCommand.ExecuteNonQuery() != 0)
                    returnBool = true;
                returnBool = false;
            return response;

        public PersonData AddJsonUser(RequestData rData)
            return AddUser(rData);

~ ~ ~

the SQL Server Database has only one table - Users :

CREATE TABLE [dbo].[Users](
[UserName] [varchar](100) NOT NULL,
[Name] [varchar](100) NOT NULL,
[EMail] [varchar](100) NOT NULL,
[Password] [varchar](100) NOT NULL,


  1. I have created Virtual directory and call the wcf, the url is ok. when calling same url in android getting exception i.e 'Not Ok'. How any reason?. I'm suspecting URL not working in android code. Tx.

  2. You have to chage the service URI ;
    In my sample I use ip = ;

    You have to put your IP ...

  3. Also be careful to change the connection string to the databse :

    connStr = "server=localhost;uid=sa;pwd=kash;database=minipassport";

  4. how to pass variables instead of passing direct values like suppose i m taking data from text boxes then what i need to do

  5. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.Android training in chennai with placement | Android Training in chennai |Android Training in Velachery

  6. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
    android development course fees in chennai | android app development training in chennai