Click here to Skip to main content
13,589,795 members
Click here to Skip to main content
Add your own
alternative version


33 bookmarked
Posted 13 Sep 2008
Licenced CPOL

Consuming .NET Web Services via the kSOAP library

, 31 Oct 2008
Rate this:
Please Sign up or sign in to vote.
Simple examples on how to use the kSOAP library to invoke Web Service methods which are defined on .NET.


As many of you know, Web Services are a great way to establish communication between distant and independent platforms.

It is straightforward to create .NET Web Services, and easier to use them from any .NET Framework enabled system. Nevertheless, when the issue comes to a non-.NET Framework system, some interoperability difficulties may appear. In order to enhance the interoperability of Web Services, the WS-I publishes profiles. The following article uses the RPC (Remote Procedure Call) messaging pattern of the widely used profile, SOAP (Simple Object Access Protocol), with .NET Web Services on the server side.

On the client side, a Java enabled Android OS installed Mobile Device will be used. For the Android OS, we need a Web Service client library that is specially designed for constrained Java environments and kSOAP provides this facility for us in an Open Source way!

Main purpose of the article is to demonstrate how to write a .NET web service that can communicate with an Android OS through kSOAP library.

Required Technologies

The versions of the software which are used during this article, are listed below:

  • SOAP v 1.1
  • kSOAP v 2.1.1 (with the WSDL patch)
  • Microsoft .NET Framework 2.0 SDK
  • Sun Microsystems Java Development Kit 1.6.0
  • Android SDK m5-rc15 for Linux-x86

(At the time the article was written, all of these software were freely downloadable from the internet.)

Using the Code

Web Service Definition (in .NET)

The source code file of the Web Service is given below. The important thing is all the method names should be unique, even if the method signatures are different. SOAPAction values must be unique across the namespace.

(Imports are not shown for brevity.)

[WebService(Namespace = "")] 
public class Service : System.Web.Services.WebService 
    public Service(){} 
    [SoapRpcMethod(), WebMethod] 
    public int GetGivenInt(int i) 
       return i; 

    [SoapRpcMethod(), WebMethod] 
    public Event GetGivenEvent(Event evnt) 
        return evnt; 

    [SoapRpcMethod(), WebMethod] 
    public int[] GetGivenIntArray(int[] array) 
        return array; 

    [SoapRpcMethod(), WebMethod] 
    public DateTime GetGivenDate(DateTime date) 
        return date; 

    [SoapRpcMethod, WebMethod]  
    public Event[] GetOnGoingEvents() 
        Event[] arrayToReturn = new Event[100]; 
        Event e ; 
        for(int i = 0; i < 100; i++) 
        e = new Event(); 
        e.Name = &quot;Event&quot;+i; 
        e.StartDate = new DateTime(2008, 6, 12); 
        e.EndDate = new DateTime(2008, 6, 20); 
        e.SubscriptionStartDate = new DateTime(2008, 3, 12); 
        e.SubscriptionEndDate = new DateTime(2008, 4, 12); 
        arrayToReturn[i] = e; 
        return arrayToReturn; 

    // Custom defined inner class to represent complex type.
    public class Event 
         // Generate properties for 
         // String Name, 
         // int Key, 
         // DateTime SubscriptionStartDate, SubscriptionEndDate, StartDate, EndDate  

Client Side Complex Type Definitions (in Java)

(Imports are not shown for brevity.)

public abstract class BaseObject implements KvmSerializable {
    public static final String NAMESPACE = &quot;;;
    public BaseObject() {

public class Event extends BaseObject
    public static Class EVENT_CLASS = new Event().getClass();    
    private String name;
    private int key;
    private Date subscriptionStartDate;
    private Date subscriptionEndDate;
    private Date startDate;
    private Date endDate;

    public Object getProperty(int index)
        switch (index) {
        case 0:
            return name;
        case 1: 
            return key;
        case 2:
            return subscriptionStartDate;
        case 3:
            return subscriptionEndDate;
        case 4:
            return startDate;
        case 5:
            return endDate;
            return null;

    public int getPropertyCount() {
        return 6;

    public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
        switch (index)
        case 0:
            info.type = PropertyInfo.STRING_CLASS;
   = "Name";
        case 1:
            info.type = PropertyInfo.INTEGER_CLASS;
   = "Key";
        case 2:
            info.type = MarshalDate.DATE_CLASS;
   = "SubscriptionStartDate";
        case 3:
            info.type = MarshalDate.DATE_CLASS;
   = "SubscriptionEndDate";
        case 4:
            info.type = MarshalDate.DATE_CLASS;
   = "StartDate";
        case 5:
            info.type = MarshalDate.DATE_CLASS;
   = "EndDate";

    public void setProperty(int index, Object value) {
        switch (index) {
        case 0:
            name = value.toString(); 
        case 1: 
            key = Integer.parseInt(value.toString());
        case 2:
            subscriptionStartDate = (Date)value;
        case 3:
            subscriptionEndDate = (Date)value;
        case 4:
            startDate = (Date)value;
        case 5:
            endDate = (Date)value;
// Getters and setters are omitted for brevity.

Defining Web Service Properties from the Client Side

Defining parameters for calling the SOAP RPC Web Service methods:

private static final String SOAP_ACTION = &quot;;;
private static final String METHOD_NAME = &quot;MethodName&quot;;
private static final String NAMESPACE = &quot;;;
private static final String URL = &quot;;;

All of the data above can be retrieved from the Web Service definition (WSDL). METHOD_NAME is the name of the method that we define in the Web Service. NAMESPACE is the namespace of the Web Service; the default is '', and can be specific to your own organization. SOAP_ACTION is the direct concatenation of NAMESPACE followed by METHOD_NAME. URL is the location where the Web Service can be accessed from. If the connection will be through SSL, you need to specify it here (e.g., https).

Set the Arguments to Pass

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

After defining our SoapObject, we can add the arguments that we are going to send to the Web Service method via the addProperty() method.

If the Web Service method does not require any parameters, no need to add any property. If one or more parameters are required, the important thing while passing a parameter is the PropertyInfo's name and type should match with the original Web Service method's parameter names.

The first example is the GetGivenInt() Web Service method which gets a primitive int parameter and returns the same primitive integer value.

PropertyInfo pi = new PropertyInfo();


The second example Web Service method is GetGivenDate() which gets a DateTime parameter and returns the same value. We need to add marshalling for the simple types that are not standardized in kSOAP, I will talk about it in the next part.

PropertyInfo pi = new PropertyInfo();
pi.setValue(new Date(System.currentTimeMillis()));

Another example is a complex type, which is going to be sent as a parameter to the GetGivenEvent() Web Service method which returns the same Event object back. Since the type Event is complex, we set the type as the Event class.

PropertyInfo pi = new PropertyInfo();
Event e = new Event();
e.setName(&quot;Antalya, Turkey&quot;);
e.setEndDate(new Date(EndDate.timeMillis()));
e.setStartDate(new Date(StartDate.timeMillis()));
e.setSubscriptionEndDate(new Date(SubscriptionEndDate.timeMillis()));
e.setSubscriptionStartDate(new Date(SubscriptionStartDate.timeMillis()));

Set Up the Envelope

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

In this example, SOAP version 1.1 is used, but both versions 1.1 and 1.2 are supported by the .NET Framework. The dotNet flag needs to be true for a .NET Web Service call from kSOAP2. In the end, the SoapObject instance 'request' is assigned as the outbound message of the SOAP call to the envelope.

Add Necessary Marshals

Marshalling is even required for simple types if they are not defined by the kSOAP library by default. The class that we are going to register for marshalling should implement the Marshal interface which has three important methods.

The readInstance() method is required to parse the XML string to the simple type when a response is retrieved. Here is the given example of the MarsalDate class; the stringToDate() method should be changed to your defined type parsing method.

public Object readInstance(XmlPullParser parser, String namespace, String name, 
              PropertyInfo expected) throws IOException, XmlPullParserException { 
   return IsoDate.stringToDate(parser.nextText(), IsoDate.DATE_TIME);

The writeInstance() method is required to parse a simple type to an XML string while sending a request. The given example is from the MarsalDate class; for other types, the parsing method should be implemented by yourself.

public void writeInstance(XmlSerializer writer, Object obj) throws IOException {
   writer.text(IsoDate.dateToString((Date) obj, IsoDate.DATE_TIME));

The register() method tells the envelope that all the XML elements suit this namespace and the name will be marshaled by the given class.

public void register(SoapSerializationEnvelope cm) {
   cm.addMapping(cm.xsd, &quot;dateTime&quot;, MarshalDate.DATE_CLASS, this);

Before calling the Web Service, the appropriate marshals should be registered to the envelope; otherwise, either request or respond will give parsing errors.

Marshal dateMarshal = new bilgiciftligi.serialization.MarshalDate();

Add Necessary Mapping

Mapping is required for complex type object parsing. The idea is similar with marshalling, but the complex type object should implement KvmSerializable and its required methods for parsing. The mapping should be added before the Web Service call.

envelope.addMapping(BaseObject.NAMESPACE, &quot;Event&quot;, new Event().getClass());

Invoke the Web Service Method

After setting the parameters, marshals, and mappings, we are ready for a call to the Web Service. The standard HttpTranport class is used for the call, but for the Android OS, we change some parts of the call for tracing; that's why it is called AnroidHttpTransport. However, the main idea is the same. Providing the SOAP_ACTION, URL, and the envelope to the call will be enough.

AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);, envelope);

Parse the Response

If the response in the envelope is not an array, after getting the response, we can directly cast it to desired type.

int receivedInt = (Integer)envelope.getResponse();
Log.v("BILGICIFTLIGI", receivedInt.toString());

Same rules apply for the complex and undefined simple types.

Date receivedDate = (Date)envelope.getResponse();
Event receivedEvent = (Event)envelope.getResponse();

If the response in the envelope is an array of any type (complex or primitive), the casting should be done into a Vector first. By using the power of Generics, we can define a Vector which contains the desired type.

Vector<Event> receivedEvents = (Vector<Event>)envelope.getResponse();
if(receivedEvents != null)
    for(Event curEvent : receivedEvents)
        Log.v("BILGICIFTLIGI", curEvent.toString());

Tracing Request and Response

The typical problem while creating a Web Service request call or getting a response is tracing the ongoing data. All the important data is moving between network interfaces, and the exception that is thrown in the application may not be so helpful sometimes. Therefore, a packet sniffer application is required to trace all the steps, and do not miss anything. Wireshark (formerly Ethereal) is one of the best network protocol analyzers which can help you on this issue. The Wireshark project is Open Source, and binaries are freely available. I bet it will be your best friend while tracing.


  • First commit created on 14 September 2008.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United States United States

You may also be interested in...


Comments and Discussions

QuestionGetting System.NullReferenceException: Object reference not set to an instance of an object. Pin
ashutiwari430-Mar-15 19:52
memberashutiwari430-Mar-15 19:52 
QuestionThe return object ksoap2 received from WCF service is anyType Pin
mone7411204-May-12 23:20
membermone7411204-May-12 23:20 
Generalmultiple layers of complex type Pin
dirsceol16-Aug-10 7:00
memberdirsceol16-Aug-10 7:00 
GeneralI have got values help me little Pin
cutesamatwork13-Jul-10 19:27
membercutesamatwork13-Jul-10 19:27 
GeneralRe: I have got values help me little Pin
HMia30-Jul-10 3:22
memberHMia30-Jul-10 3:22 
GeneralArray parameter Pin
fadi wedyan24-May-10 0:19
memberfadi wedyan24-May-10 0:19 
GeneralComplex types Pin
HMia17-May-10 3:17
memberHMia17-May-10 3:17 
GeneralA note on the dotNet Flag.... Pin
sslipknot30007-Apr-10 6:04
membersslipknot30007-Apr-10 6:04 
Generalhelp me , please Pin
Karla O´neill24-Mar-10 4:31
memberKarla O´neill24-Mar-10 4:31 
Generalthanks... Pin
Orian Beltrame5-Feb-10 7:55
memberOrian Beltrame5-Feb-10 7:55 
GeneralGreat article Pin
Predrag Tomasevic28-Dec-09 10:04
memberPredrag Tomasevic28-Dec-09 10:04 
QuestionWhat about ClassCastException ? Pin
Member 399156320-Jun-09 9:54
memberMember 399156320-Jun-09 9:54 
GeneralWeb service returns vector Pin
barnyy25-Apr-09 0:57
memberbarnyy25-Apr-09 0:57 
Generalksoap2 WSDL patch Pin
softsky29-Oct-08 2:07
membersoftsky29-Oct-08 2:07 
GeneralRe: ksoap2 WSDL patch Pin
sacoskun31-Oct-08 8:49
membersacoskun31-Oct-08 8:49 
Generalthanks Pin
SirAsad23-Oct-08 5:47
memberSirAsad23-Oct-08 5:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.180618.1 | Last Updated 31 Oct 2008
Article Copyright 2008 by sacoskun
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid