How to Consume Web Services from Android Applications Using kSOAP2

Android API does not provide support for Web services. Thus, Web services are consumed using a third-party libraries. One example is kSOAP2 (http://ksoap2.sourceforge.net/), optimized for Android.

The libraries need to be added to the project in order to be used. This library is based on SOAP and there is no need to generate a proxy/stub to call Web services methods.

Here is an exemple of a simple call to a method provided by a Web service:

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
//...
try
{
SoapObject request = new SoapObject(NAMESPACE, GET_INTREBARE);

// add paramaters and values
request.addProperty("idTest", idTest);
request.addProperty("idIntrebare", idIntrebare);

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

//Web method call
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL_WS);
androidHttpTransport.call(NAMESPACE + GET_INTREBARE, envelope);
//get the response
SoapObject result = (SoapObject) envelope.getResponse();

//the response object can be retrieved by its name: result.getProperty("objectName")
}
catch (Exception e)
{
e.printStackTrace();
}

Some explanations of the code:

  • A SOAP envelope is created using the SoapSerializationEnvelope class (specifying the SOAP version) and the request details are added to the envelope body (using SoapObject class).
  • The HttpTransportSE class is used to make the actual call of the Web service method, the envelope being passed as parameter. The result is retrieved from the response part of the envelope.
  • It is very important to send the right parameters to the methods. In this example, the parameters used in these calls are initialized as follows:
    • NAMESPACE = “http://tempuri.org/”; – Web service namespace; in this example the default namespace is used
    • URL_WS = “http://server/Service.asmx”; – Web service URL
    • GET_INTREBARE = “GetIntrebare”; – Web service method name
    • idTest, idIntrebare – the parameters used by GetIntrebare method

Using wrong values for these parameters will lead to Web service method call to fail.

In order to use Web services the application needs special permission. Permissions are stored in AndroidManifest.xml file. For this mobile application, the following line has to be added: