Call SOAP Web Service from Android application


This article will cover how to call a soap web service from your android application.

Here I am giving you a sample calculator application. Let us see the WSDL file of the web service

 <?xml version="1.0" encoding="UTF-8" ?>
 <wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://cts.calc.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:ax21="http://cts.calc.com/xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://cts.calc.com">
<wsdl:documentation>Please Type your service description here</wsdl:documentation>
 <wsdl:types>
 <xs:schema xmlns:ax22="http://cts.calc.com/xsd" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://cts.calc.com">
<xs:import namespace="http://cts.calc.com/xsd" />
 <xs:element name="doService">
 <xs:complexType>
 <xs:sequence>
<xs:element minOccurs="0" name="c" nillable="true" type="ax22:Calculator" />
</xs:sequence>
</xs:complexType>
</xs:element>
 <xs:element name="doServiceResponse">
 <xs:complexType>
 <xs:sequence>
<xs:element minOccurs="0" name="return" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
 <xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://cts.calc.com/xsd">
 <xs:complexType name="Calculator">
 <xs:sequence>
<xs:element minOccurs="0" name="a" type="xs:int" />
<xs:element minOccurs="0" name="b" type="xs:int" />
<xs:element minOccurs="0" name="operator" nillable="true" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:schema>
</wsdl:types>
 <wsdl:message name="doServiceRequest">
<wsdl:part name="parameters" element="ns:doService" />
</wsdl:message>
 <wsdl:message name="doServiceResponse">
<wsdl:part name="parameters" element="ns:doServiceResponse" />
</wsdl:message>
 <wsdl:portType name="CalcServicePortType">
 <wsdl:operation name="doService">
<wsdl:input message="ns:doServiceRequest" wsaw:Action="urn:doService" />
<wsdl:output message="ns:doServiceResponse" wsaw:Action="urn:doServiceResponse" />
</wsdl:operation>
</wsdl:portType>
 <wsdl:binding name="CalcServiceSoap11Binding" type="ns:CalcServicePortType">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
 <wsdl:operation name="doService">
<soap:operation soapAction="urn:doService" style="document" />
 <wsdl:input>
<soap:body use="literal" />
</wsdl:input>
 <wsdl:output>
<soap:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
 <wsdl:binding name="CalcServiceSoap12Binding" type="ns:CalcServicePortType">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
 <wsdl:operation name="doService">
<soap12:operation soapAction="urn:doService" style="document" />
 <wsdl:input>
<soap12:body use="literal" />
</wsdl:input>
 <wsdl:output>
<soap12:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
 <wsdl:binding name="CalcServiceHttpBinding" type="ns:CalcServicePortType">
<http:binding verb="POST" />
<wsdl:operation name="doService">
<http:operation location="CalcService/doService" />
<wsdl:input>
<mime:content type="text/xml" part="doService" />
</wsdl:input>
 <wsdl:output>
<mime:content type="text/xml" part="doService" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="CalcService">
<wsdl:port name="CalcServiceHttpSoap11Endpoint" binding="ns:CalcServiceSoap11Binding">
<soap:address location="http://localhost:8080/CalcService1.5/services/CalcService.CalcServiceHttpSoap11Endpoint/" />
</wsdl:port>
 <wsdl:port name="CalcServiceHttpSoap12Endpoint" binding="ns:CalcServiceSoap12Binding">
<soap12:address location="http://localhost:8080/CalcService1.5/services/CalcService.CalcServiceHttpSoap12Endpoint/" />
</wsdl:port>
 <wsdl:port name="CalcServiceHttpEndpoint" binding="ns:CalcServiceHttpBinding">
<http:address location="http://localhost:8080/CalcService1.5/services/CalcService.CalcServiceHttpEndpoint/" />
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

This web service is expecting a payload Calculator.xml

<Calculator>
           <a>2</a>
           <b>5</b>
           <operator>+</operator>
    </Calculator>

The classes should be like this


public class Calculator {
 private int a;
 private int b;
 private String operator;

 public int getA() {
  return a;
 }

 public void setA(int a) {
  this.a = a;
 }

 public int getB() {
  return b;
 }

 public void setB(int b) {
  this.b = b;
 }

 public String getOperator() {
  return operator;
 }

 public void setOperator(String operator) {
  this.operator = operator;
 }
}

---------------------------------------------------------------

public interface CalcInt {
  public int doService(Calculator c);
}

-------------------------------------------------------------------

public class CalcService implements CalcInt {

	public int doService(Calculator c) {
	  try{
		if(c.getOperator()!=null && c.getOperator().equals("+"))
			return c.getA()+c.getB();
		else if(c.getOperator()!=null && c.getOperator().equals("-"))
			return c.getA()-c.getB();
		else if(c.getOperator()!=null && c.getOperator().equals("*"))
			return c.getA()*c.getB();
		else if(c.getOperator()!=null && c.getOperator().equals("/"))
			return c.getA()/c.getB();
		return 0;
          }catch(Exception e){

	    e.printStackTrace();
	  }
	}

Now let us see the Android application .Here I mentioned step by step process ok
1. Create an android application by the help of your IDE (eclipse) with activity name Calculate.

2. Edit AndroidManifest.xml give permission inside the manifest tag

<uses-permissionandroid:name="android.permission.INTERNET"
/>

3. Edit main.xml in layout and one more xml for calulator view calcview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
   <include android:id="@+id/calcview" layout="@layout/calcview" />
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>
-------------------calcview.xml------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
  android:layout_height="match_parent">
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
  android:layout_height="match_parent">

 <TableRow android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
   android:layout_height="wrap_content">

  <EditText android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:numeric="integer|decimal"></EditText>

  <Spinner android:layout_height="wrap_content" android:id="@+id/spinner1"
   android:layout_width="wrap_content"></Spinner>
  <EditText android:id="@+id/editText2"
   android:numeric="integer|decimal"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"></EditText>
 </TableRow>
 <TableRow android:id="@+id/tableRow2"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">

  <Button android:id="@+id/button1"
   android:onClick="doCalculation"
      android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Calculate"></Button>
 </TableRow>
 <TableRow android:id="@+id/tableRow3" android:layout_width="wrap_content"
  android:layout_height="wrap_content">
  <EditText android:id="@+id/editText3" android:layout_width="wrap_content"
   android:layout_height="wrap_content"></EditText>
 </TableRow>

</TableLayout>
</LinearLayout>

4. Now let us include the ksoap2 API for SOAP . Douwnload jar file from the following location and map with your project (Add library in build path in eclipse).

http://ksoap2-android.googlecode.com/files/ksoap2-android-assembly-2.4-jar-with-dependencies.jar

5. Create Calculator class which implements KvmSerializable

import java.util.Hashtable;

import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;

public class Calculator implements KvmSerializable{
 public int a;
 public int b;
 public String operator;

 public Calculator(){}

     public Calculator(int a1, int b1, String operator1) {

         a = a1;
         b = b1;
         operator = operator1;
     }

     public Object getProperty(int arg0) {

         switch(arg0)
         {
         case 0:
             return a;
         case 1:
             return b;
         case 2:
             return operator;
         }

         return null;
     }

     public int getPropertyCount() {
         return 3;
     }

     public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
         switch(index)
         {
         case 0:
             info.type = PropertyInfo.INTEGER_CLASS;
             info.name = "a";
             break;
         case 1:
             info.type = PropertyInfo.INTEGER_CLASS;
             info.name = "b";
             break;
         case 2:
             info.type = PropertyInfo.STRING_CLASS;
             info.name = "operator";
             break;
         default:break;
         }
     }

     public void setProperty(int index, Object value) {
         switch(index)
         {
         case 0:
             a = Integer.parseInt(value.toString());
             break;
         case 1:
             b = Integer.parseInt(value.toString());
             break;
         case 2:
             operator = value.toString();
             break;
         default:
             break;
         }
     }

}

6. Now the major part: Edit the Calculate activity class and call the webservice

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class Calculate extends Activity  {
    /** Called when the activity is first created. */

   static Spinner operator = null;
   private static final String SOAP_ACTION = "doService";
 private static final String METHOD_NAME = "doService";
 private static final String NAMESPACE = "http://cts.calc.com";
 private static final String URL =
  "http://10.230.139.74:8080/CalcService1.5/services/CalcService?wsdl";
 private SoapObject resultRequestSOAP = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        operator = (Spinner)findViewById(R.id.spinner1);
        String array_spinner[]  =  new String[4];
        array_spinner[0] = "+";
        array_spinner[1] = "-";
        array_spinner[2] = "*";
        array_spinner[3] = "/";
        ArrayAdapter<?> adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, array_spinner);
        operator.setAdapter(adapter);

    }

    public void doCalculation(View view){
     String firstNo =
   ((EditText) findViewById(R.id.editText1))
   .getText().toString();
  String secondNo =
   ((EditText) findViewById(R.id.editText2))
   .getText().toString();
  String operator = ((Spinner) findViewById(R.id.spinner1)).getSelectedItem().toString();
  callWebService(firstNo,secondNo,operator );
    }

    public String callWebService(String firstNo, String secondNo,String operator ){
     String result = "0";
     try {
      SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
      AndroidHttpTransport androidHttpTransport =
       new AndroidHttpTransport(URL);

   PropertyInfo p1 = new PropertyInfo();
   Calculator C = new Calculator();
   C.a=Integer.parseInt(firstNo);
   C.b=Integer.parseInt(secondNo);
   C.operator=operator;

   p1.setName("C");
         p1.setValue(C);
         p1.setType(C.getClass());
         request.addProperty(p1);

   SoapSerializationEnvelope envelope =
    new SoapSerializationEnvelope(SoapEnvelope.VER11);

   envelope.dotNet=true;
   envelope.setOutputSoapObject(request);

   // Make the soap call.
   androidHttpTransport.call(SOAP_ACTION, envelope);

   Object results =(Object)envelope.getResponse();
   //to get the data String resultData=result.getProperty(0).toString();
   String temp = results.toString();
   if(temp.equals("0")){
    temp = "The result is 0";
   }
   System.out.println("Result"+temp);
   /** Show the suggestions in a text area field called
    * lblStatus */
   ((TextView) findViewById(R.id.editText3)).setText(temp
     .toString());
  } catch (Exception aE) {
   System.out.println(aE.toString());

   ((TextView) findViewById(R.id.editText3)).setText(aE.getMessage());
   aE.printStackTrace();
  }

     return result;
    }

}

END

Advertisements

About Praveen Orathel

I am a java web application developer.
This entry was posted in Uncategorized. Bookmark the permalink.

24 Responses to Call SOAP Web Service from Android application

  1. pradeep says:

    This is a very good article

  2. Shreya Gupta says:

    On generating the web service for CalcService, when doService method is invoked, it shows exception: The AXIS engine could not find a target service to invoke! targetService is CalcService. And the wsdl generated is different from the one you have posted.

    • sorry for the late reply
      try to create the normal web client using wsdl file. And approch the same if you are succeeded.
      please reach me if you have any more clarification required

  3. Mara says:

    Hello,

    I am trying to deploy a web service on jboss and call it from android. I understood the part of calling the webservice, but i am stuck on deploying it.
    Could you give some details on creating the other xml files needed (mapping, webservices,web ) and building the war that will be deployed .
    What is the name of the package that contains the classes of the web services .calc.com or com.calc.cts ?

    Thank you.

    • sorry for the late reply
      It is no matter of consern wheather you are using tomcat or jboss or ws … you can call the service from client.
      you are creating your client based on the wsdl file.

  4. Thanks for the post, just what I was looking for. Official documentation is really really poor. Great job

  5. esh says:

    Hi please help me…
    I have done a simple project to call wcf web service using ksoap2. But when it calls
    envelope.getResponse();
    I’m running web service in localhost.
    it gives error saying ————–
    “SoapFault – faultcode: ‘a:ActionNotSupported’ faultstring: ‘The message with Action ‘GetString’ cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).’ faultactor: ‘null’ detail: null”

    please help me some one

    is this values correct that I have assigned,

    private static final String SOAP_ACTION = “GetString”;
    private static final String OPERATION_NAME = “GetString”;
    private static final String WSDL_TARGET_NAMESPACE = “http://tempuri.org/”;
    private static final String SOAP_ADDRESS = “http://10.0.2.2:14089/Service1.svc?wsdl”;

  6. Can you suggest any tutorial where it is describe step by step for request response app.

  7. Sir I implement all the code correctly but its show error
    Cannot serialize:com.hj.s.
    Calcultor@44e380b8

  8. Hi,
    This works great for Document based webservices. What if you want to parse rpc based webservices.

  9. mamatha says:

    Hai Please help me
    i done webservices in net .I dnt know which webservices i use for android application.can u tel me
    here is my xml file

    4

    painter ,sr nagar

    5

    painter ,kphb

    7

    painter ,hi tech city

    8

    painter ,ameerpet

    9

    painter ,banjara hills

    plz help me anyone

  10. you can create your web service using any language like .Net.
    The only thing is, this blog describing about how to send a pay load to a web service using SOAP.
    Which means you can access your hosted web service using its service URL [Eg: https://serviceurl , you can see your wsdl ]

  11. krishnaveni says:

    Hi Praveen…..
    its fine tutorial…But i wish to need how is connecting mysql database using ksoap2 webservices…how is retrieve data from mysql database through ksoap2 webservices.i found many tutorials..but am not clearly understand…so send me clear tutorial…please help me praveen…thanks in advance.

  12. Mohammed Raes says:

    Hi I am trying to create and android web service client for a java web service …. I used axis to generate the java code from the wsdl but when i try to run the app it says java.lang.NoClassDefFoundError… i tried creating a jar file with the class files and loaded it as an external jar .But still the same error !!!!! The web services is SOAP based .
    Please help me .Very important my job is at stake

    • Have you created the stub ?. which class you are getting issue, after creating the client using axis make it in jar and use it as external lib

      • Mohammed Raes says:

        well as I mentioned in my post I did try using it as an external lib but still the same error occurs .The proxy class is not found which creates the problems for the execution of the app.Thank you for replying .I have been trying to find alternatives all over the internet but since our wsdl doesn’t have the standard format ,most wsdl2jav gen command line tools reject saying that it contains multiparts so I had to use the clent files generated by axis but the problem is this NoClassDefFoundError which is coming with/without the lib files … in fact I tried removing the java files from the project but then the imports dont work despite trying to use the external lib… I looked at the project folder and found that the class files do exist in the classes folder but they are not found by android/eclipse .So thats the situation of my project … right now i have shifted to low-level approach where i manually parse the XML response using DOM parser which makes it very complex since our wsdl has very complex types .Please do check and give me a solution to the problem .

  13. Pingback: World of Android « Thoughts To Inspire

  14. hello sir, in android where should i write wsdl code, i don’t know the path

  15. Raja says:

    Hi,
    I am trying to consume webservice using java in android app. I am getting some error.
    This is my webservices:




    This is my Android code:
    package com.example.ws1;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.PropertyInfo;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.widget.TextView;

    public class MainActivity extends Activity
    {
    private static final String SOAP_ACTION = “http://tempuri.org/logon”;
    private static final String METHOD_NAME = “logon”;
    private static final String NAMESPACE = “http://tempuri.org/type”;
    private static final String URL = “http://192.168.7.86:90/CRM7/eware.dll/webservices.wsdl”;
    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tv=(TextView)findViewById(R.id.text1);
    call();
    }
    public void call()
    {
    try {

    PropertyInfo pi = new PropertyInfo();
    pi.setName(“username”);
    pi.setValue(“admin”);
    pi.setName(“password”);
    pi.setValue(“test@123”);

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty(pi);
    //request.addAttribute(“username”, “admin”);
    //request.addAttribute(“password”, “test@123”);

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

    HttpTransportSE androidHttpTransports = new HttpTransportSE(URL);
    androidHttpTransports.call(SOAP_ACTION, envelope);

    SoapObject response = (SoapObject) envelope.bodyIn;
    String results = response.getProperty(0).toString();
    //Object result = (Object)envelope.getResponse();

    tv.setText(results.toString());
    } catch (Exception e) {
    tv.setText(e.getMessage());
    }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
    }
    }

    I am calling the method “logon” and passing the parameter as ‘username’ and ‘password’
    after calling that function I am getting an error

    org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG @4:81 in java.io.InputStreamReader@4052e620)

    I just try to comment the below line also getting same error:
    envelope.dotNet=true;

    Please any one help on this..!

    Regards,
    Raja M

    • Raja says:

      Hi,
      Please get my webservice here:






      Any workaround I need to do ..?

      Regards,
      Raja M

  16. Prashil Thakur says:

    As per standard SOAP/XML based approach. We have to generate client stubs from the wsdl provided. This code will consume the webservice and give us the appropriate output after calling web servicefrom client. So is there any standard plugin provided in android sdk to generate the code. The AXIS and AXIS-2 plugins are already there in eclipse but in some cases (Input Parameters enums) it gives SOAP_FAULT. So I just wanted to know that android provides in built soap support through some library or not?

  17. Payday Loans says:

    Hey! I could have sworn I’ve been to this site before but after reading through some of the post I realized it’s new
    to me. Anyhow, I’m definitely glad I found it and I’ll be bookmarking
    and checking back frequently!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s