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 Android.java source code is on Google Code :
http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/src/net/learn2develop/AndroidViews/

The full Eclipse Indigo 3.7 - Android  project zipped on Google Docs :
https://docs.google.com/leaf?id=0BzKVfKe--t_cMDU5OTU5MDQtNDQzOC00YjE3LTlhODgtYjE1ZDhmZWFmZjc1&hl=en_GB


All files of the WCF RESTful Web Service are also on Google Code :
http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/RestService

The full Visual Web Developer project -  VWD  Express 2010 also on Google Docs :
https://docs.google.com/leaf?id=0BzKVfKe--t_cODIwZWE2M2QtZTUwMy00Yjg1LTljMjUtYTA3MGI4YmM5OGZm&hl=en_GB

First we tried to post XML formatted data to a WCF Web Service with FIDDLER ( step 5 ) :
http://pantestmb.blogspot.com/2011/10/pass-multiple-body-parameters-wcf-rest.html

Then tried to post JSON data to a WCF Web Service with FIDDLER ( step 6 ) :
http://pantestmb.blogspot.com/2011/10/wcf-rest-fiddler-json-request-body.html

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 :


http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/src/net/learn2develop/AndroidViews/SavePerson.java

package net.learn2develop.AndroidViews;


import android.app.Activity;
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 = "http://192.168.61.3/RestServicePost/RestServiceImpl.svc";

@Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       setContentView(R.layout.main);
       // 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()
                .object()
                    .key("rData")
                        .object()
                            .key("details").value("bar|bob|b@h.us|why")
                        .endObject()
                    .endObject();
         
            StringEntity entity = new StringEntity(vehicle.toString());
         
            Toast.makeText(this, vehicle.toString() + "\n", Toast.LENGTH_LONG).show() ;
         
            request.setEntity(entity);
         
            // 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() ;
         
         

}  
}


http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/RestService/IRestServiceImpl.cs


      [OperationContract]
        [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" :
 http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/RestService/RequestData.cs


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





The string  "bar|bob|b@h.us|why" of the JSONStringer is hard-coded to simplify things ;
After being parsed - it ends up in the SQLS table "Users" : 





http://code.google.com/p/jtelmon/source/browse/trunk/AndroidViews/RestService/RestServiceImpl.svc.cs
AddUser is the function triggered by the POST WCF Webservice
http://192.168.61.3/RestServicePost/RestServiceImpl.svc/json/adduser
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);
            try
            {
                dbConn.Open();
                if (dbCommand.ExecuteNonQuery() != 0)
                {
                    returnBool = true;
                }
                dbConn.Close();
            }
            catch
            {
                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,


3 comments:

  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.

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

    http://192.168.61.3/RestServicePost/RestServiceImpl.svc

    You have to put your IP ...

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

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

    ReplyDelete