Tuesday, August 18, 2009

Connecting to .NET web service from Android

If you are having trouble using .NET Web Services with the Android Platform, you have probably reached to the solution here.

I am here demonstrating the steps using which you can consume data from the .NET web service in your android app. In order to use .Net web Service from your android application you need to first download the ksoap2 android API. Follow the link to download ksoap2 API for android.

After downloading the API, extract the zip file to the file system. Open your Android Project and navigate to the Project Properties. In the project properties go to Java Build Path and say Add External JARs.

Add the reference to the extracted ksoap2-j2se-full-2.1.2.jar file from the downloaded API. You are now ready to use ksoap2 to connect to the .NET web service via Android.

Let’s assume a .NET web service with two methods “Hello World” that returns a string and “Add” that accepts two numbers and returns their sum. Following is the WSDL file of the web service.

From the above WSDL file we get the following Information about the web service:
  • NameSpace: http://localhost/TestWebService/
  • Web Service URl: http://TestServer/Test/Service.asmx
  • Method “Hello World” SoapAction URL: http://localhost/TestWebService/HelloWorld
  • Method “Hello World” Output Type: String
  • Method “Add” SoapAction URL: http://localhost/TestWebService/Add
  • Method Hello World Input Type: Int, Int
  • Method Hello World Output Type: Int
In order to use this Web Service with our android app:
  1. Open the java file from where you would like to access the Web Service

  2. Include the class library for ksoap2

    import org.ksoap2.*;
    import org.ksoap2.serialization.*;
    import org.ksoap2.transport.*;
    import org.w3c.dom.Text;


  3. Define Web Service Properties in the class

    private static final String NAMESPACE = "http://localhost/TestWebService/" ;
    private static final String URL = " http://TestServer/Test/service.asmx";
    private static final String HelloWorld_SOAP_ACTION = "http://localhost/TestWebService/HelloWorld";
    private static final String METHOD_NAME1 = "HelloWorld";
    private static final String Add_SOAP_ACTION = "http://localhost/TestWebService/Add";
    private static final String METHOD_NAME2 = "Add";


  4. Add methods to call the web service methods and retrieve the results

    public void GetHelloWorld() {

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
    SoapSerializationEnvelope envelope =
    new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try
    {
    androidHttpTransport.call(HelloWorld_SOAP_ACTION, envelope);
    java.lang.String receivedString = (String)envelope.getResponse();

    }
    catch(Exception e)
    {
    }

    }
    public void GetAdd() {

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);

    PropertyInfo num1 = new PropertyInfo();
    num1.setName("a");
    num1.setValue(5);
    request.addProperty(num1);

    PropertyInfo num2 = new PropertyInfo();
    num2.setName("b");
    num2.setValue(9);
    request.addProperty(num2);

    SoapSerializationEnvelope envelope =
    new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try
    {
    androidHttpTransport.call(Add_SOAP_ACTION, envelope);
    java.lang.Integer receivedInt = (Integer)envelope.getResponse();

    }
    catch(Exception e)
    {
    }

    }


  5. If you app require access to an array, you can use the following code:

    ArrayList<String> a = new ArrayList<String>();
    try
    {
    androidHttpTransport.call(SOAP_ACTION, envelope);
    java.util.Vector<Object> receivedStrings = (java.util.Vector<Object>)envelope.getResponse();
    if(receivedStrings != null)
    {
    for(Object curStrings : receivedStrings)
    {
    a.add(curStrings.toString());
    }
    }
    }
    catch(Exception e)
    {
    }

I hope the above steps helps you if this is what you are looking for.

41 comments:

  1. Hi,
    Thanks for your post. I had been struggling in writing a code that calls a .net web service from Android. I followed the code you posted. The call is peformed correctly with one problem. The parameters passed are always null. I tried assing integers, floats, strings and its always the same. Please any hint why this is happening?
    Thanks,

    ReplyDelete
  2. Yes, I have the same issue as wedyan. Please advise on why this is occurring.

    ReplyDelete
  3. The same problem!! Please could you help us?

    ReplyDelete
  4. I found it. HERE is the solution

    forums.sun.com/thread.jspa?threadID=5343657

    ReplyDelete
  5. please help me, I want to connect to sql server from android and i don't find how to do this,

    ReplyDelete
  6. nice apps, really informative also, helped me allot.

    ReplyDelete
  7. This may help you
    http://bimbim.in/post/2010/10/08/Android-Calling-Web-Service-with-complex-types.aspx

    ReplyDelete
  8. Hi!
    I keep having the same problem as wedyan,

    The call is peformed correctly with one problem. The parameters passed are always null...

    anyone knows how to solve this?

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Hi Tixa,

    Instead of using
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);

    PropertyInfo num1 = new PropertyInfo();
    num1.setName("a");
    num1.setValue(5);
    request.addProperty(num1);

    PropertyInfo num2 = new PropertyInfo();
    num2.setName("b");
    num2.setValue(9);
    request.addProperty(num2);

    just use

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);

    request.addProperty("a", "5");
    request.addProperty("b", "9");

    ReplyDelete
  11. Hi! I've found the problem... it was a mistake i made with the name of the namespace in the Web Service ;)

    I changed it to ..localhost/ and it worked! thanks anyway!

    ReplyDelete
  12. @Tixa,

    What do you mean you changed it to localhost? This might work from an emulator but will not work from an android device. Right?

    tonytony

    ReplyDelete
  13. i changed it to localhost but is just an example for the namespace!

    The namespace was wrong in the client side... my bad!

    ReplyDelete
  14. I'm having the same issue. I've tried both:

    PropertyInfo num1 = new PropertyInfo();
    num1.setName("a");
    num1.setValue(5);
    request.addProperty(num1);

    and

    request.addProperty("a", "5");

    and i'am always getting a null. Can anyone help me? Thanks

    ReplyDelete
  15. Have you confirm the namespace in the client side? most likely something is missing or wrong, like a '/', i have friends with the same problem and it is always the namespace.

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. I solved it by changing the namespace to IP:port instead of "localhost". Now I have issues by passing double values to the service. It says they can't be serialized. Any advice? Thanks a lot

    ReplyDelete
  18. http://pantestmb.blogspot.com/2011/02/personpassport4asmx.html

    ReplyDelete
  19. The above code for accessing an array does not work, I get a casting error. Does anyone know how to receive a string array?

    ReplyDelete
  20. This is how you can receive a string array:

    SoapObject oResponse = (SoapObject)oEnvelope.getResponse();

    ArrayList oStringList = new ArrayList();
    for(int i = 0; i < oResponse.getPropertyCount(); i++)
    oStringList.add(oResponse.getProperty(i).toString());

    ReplyDelete
  21. When I use envelope.getResponse() to get result, I have an error ClassCastException. Can you give my a explanation why it is.

    ReplyDelete
  22. Hey i have one problem i get SoapObject in response and i want XML data out of it or in response i want xml data can anyone help ? thanks in advance

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. please,
    i want code like this but with Blackberry
    if you can
    sent it to me at:
    alihosny_cs@yahoo.com

    ReplyDelete
  25. I am a beginner in java-eclipse I have a PFE on geolocation based smarthpnes is an android application I have a problem on the web server connection and I want to develop a feature on the traceability and authentication, please help me it's urgent

    ReplyDelete
  26. I'm sorry my program on android sdk 8 (API 15)

    ReplyDelete
  27. I get this error when I run the app:

    06-06 09:12:24.341: E/dalvikvm(272): Could not find class 'org.ksoap2.serialization.SoapObject', referenced from method com.mtb.android.AndroidActivity.GetLoginResults

    What could be wrong

    ReplyDelete
    Replies
    1. I made the same mistake. When your looking at the project properties and specifically the build path. I'm assuming you've added the KSoap2 library as per this tutorial but what is missing is that after adding the KSoap2 library you need to go to the tab "Order and Export" (still under the Java Build Path category) and make sure the KSoap2 jar file is checked.

      Delete
  28. This comment has been removed by the author.

    ReplyDelete
  29. package com.example.webservice;
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.PropertyInfo;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;




    public class add {


    public final String SOAP_ACTION="http://tempuri.org/Add";
    public final String OPERATION_NAME="Add";
    public final String WSDL_TARGET_NAMESPACE="http://tempuri.org/";
    public final String SHOP_ADDRESS="http://10.0.2.2/Web Service/Service.asmx";
    public add()
    {
    }

    public String Call(int a,int b)
    {


    SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
    PropertyInfo pi=new PropertyInfo();
    pi.setName("a");
    pi.setValue(a);
    pi.setType(Integer.class);
    request.addProperty(pi);
    pi=new PropertyInfo();
    pi.setName("b");
    pi.setValue(b);
    pi.setType(Integer.class);
    request.addProperty(pi);

    SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet=true;
    envelope.setOutputSoapObject(request);

    HttpTransportSE httpTransport=new HttpTransportSE(SHOP_ADDRESS);

    httpTransport.debug=true;
    Object response=null;

    try
    {

    httpTransport.call(SOAP_ACTION,envelope);
    response=envelope.getResponse();
    }

    catch (Exception e) {
    // TODO: handle exception

    response= e.toString();

    }
    return response.toString();
    }
    }
    i get Java.io.IOException BufferedInputStream error.
    i cant solve this errore\.
    please give me proper answer as soon as posible.

    ReplyDelete
    Replies
    1. hi pankaj,
      i am facing the problem ,i need ur help ,actually i have connect my android app with the ms sql server 2008 r2 db and i have to retrieve the table data in my android app,can u help me for doing this ..if u know this ,how to do it plz suggest me and help me ...i am waithing for ur reply
      my mail id is : pradipkarad@gmail.com

      Delete
  30. Good one keep uploading such type of things will return to read your blog...

    Secure Web Design

    ReplyDelete
  31. Hi, this article is good and I have small query. As I want to send a data mostly like a ArrayList of data to my asmx web service. and that data is in this format Itemname##Quantity. but I am getting an exception of cannot serialize Itemname##Quantity at the line httpTransport.call(Soap_Action, envelope);

    I dont how to serialize this line?
    any help please

    ReplyDelete
  32. Nice work, your blog is concept oriented ,kindly share more blogs like this
    .NET Online Course Bangalore

    ReplyDelete
  33. If you are looking for more information about flat rate locksmith Las Vegas check that right away. appcloner's website

    ReplyDelete
  34. Keep up the good work; I read few posts on this website, including I consider that your blog is fascinating and has sets of the fantastic piece of information.



    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery


    ReplyDelete