How to Call Web Service in Android Using SOAP

In this tutorial, we will learn how to call a Web Service using SOAP (Simple Object Access Protocol).

Introduction


In this tutorial, we will learn how to call a Web Service using SOAP (Simple Object Access Protocol).

Prerequisites

Web Service, SOAP envelope, WSDL (Web Service Definition Language)

What is SOAP?


SOAP is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission. The following is the structure of SOAP Envelope:

AndWeb1.jpg
 
Step 1

First create a "New Android Project". Name it "WebServiceDemo" like below.

AndWeb2.jpg

AndWeb3.jpg

AndWeb4.jpg

Step 2

Now right-click on your "WebServiceDemo" project and select "New -> Folder"

AndWeb5.jpg


Now, give it a name it "lib". We need to add a SOAP library into this directory.

AndWeb6.jpg

Step 3

Now download the attached library named "ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar". Copy that file and paste it into the "lib" directory.

After copying, do the following steps:
  1. Right-click on the project.
  2. Go "Build Path -> Configure Build Path"

    AndWeb7.jpg
     
  3. Now, click on "Add Jars" and select ".jar" file from "project -> lib" directory.

    AndWeb8.jpg
     
  4. Click on "Ok" to finish the procedure of adding library to Android application.

Step 4

Next we need to create a layout of screen. To do so, go to "WebServiceDemo -> res -> layout -> main.xml"

Open this xml file in editing mode, and place below code.

Main.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.     <TextView  
  7.         android:id="@+id/textView1"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:text="Fahrenheit"  
  11.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  12.     <EditText  
  13.         android:id="@+id/txtFar"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content" >  
  16.         <requestFocus />  
  17.     </EditText>  
  18.     <TextView  
  19.         android:id="@+id/textView2"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="Celsius"  
  23.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  24.     <EditText  
  25.         android:id="@+id/txtCel"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="wrap_content" />  
  28.     <LinearLayout  
  29.         android:id="@+id/linearLayout1"  
  30.         android:layout_width="match_parent"  
  31.         android:layout_height="wrap_content" >  
  32.         <Button  
  33.             android:id="@+id/btnFar"  
  34.             android:layout_width="wrap_content"  
  35.             android:layout_height="wrap_content"  
  36.             android:layout_weight="0.5"  
  37.             android:text="Convert To Celsius" />  
  38.         <Button  
  39.             android:id="@+id/btnCel"  
  40.             android:layout_width="wrap_content"  
  41.             android:layout_height="wrap_content"  
  42.             android:layout_weight="0.5"  
  43.             android:text="Convert To Fahrenheit" />  
  44.     </LinearLayout>  
  45.     <Button  
  46.         android:id="@+id/btnClear"  
  47.         android:layout_width="match_parent"  
  48.         android:layout_height="wrap_content"  
  49.         android:text="Clear" />  
  50. </LinearLayout>  
This will create simple following screen.
 
AndWeb9.jpg


Step 5

Now, find out any Web Service, make sure that you can view its WSDL file by writing "?wsdl" after that address.

For example, you have a web service like http://www.w3schools.com/webservices/tempconvert.asmx",  so to view the WSDL file, simply write "?wsdl" after this address like:
 
http://www.w3schools.com/webservices/tempconvert.asmx?WSDL". 

You are now done with the Web Service part from the internet. Now you need to extend some portion of the WSDL file. Open the first link in your browser, it will display 2 conversions for you: 
  • CelsiusToFahrenheit

  • FahrenheitToCelsius

Select anyone of them, and you will see following screen:

AndWeb10.jpg

For CelsiusToFahrenheit: 
  1. SOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";

  2. NAMESPACE = "http://tempuri.org/";

  3. METHOD_NAME = "CelsiusToFahrenheit";

  4. URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";

For FahrenheitToCelsius:

  1. SOAP_ACTION = "http://tempuri.org/FahrenheitToCelsius";

  2. NAMESPACE = "http://tempuri.org/";

  3. METHOD_NAME = " FahrenheitToCelsius ";

  4. URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";

Step 6

You need to understand some classes before proceeding to use a Web Service.

  1. SoapObject (

    A simple dynamic object that can be used to build SOAP calls without implementing KvmSerializable. Essentially, this is what goes inside the body of a SOAP envelope - it is the direct subelement of the body and all further sub elements. Instead of this class, custom classes can be used if they implement the KvmSerializable interface.

    Constructor:

    SoapObject (java.lang.String namespace, java.lang.String method)

  2. SoapSerializationEnvelope

    This class extends the SoapEnvelope with Soap Serialization functionality.

    Constructor:

    SoapSerializationEnvelope (int version)

    Fields:

    Type Field Description
    boolean dotNet Set this variable to true for compatibility with what seems to be the default encoding for .Net-Services.

    Methods:

    Return Type Method Name Description
    void setOutputSoapObject(java.lang.Object soapObject) Assigns the object to the envelope as the outbound message for the soap call.
  3. HttpTransportSE (org.ksoap2.transport.HttpTransportSE)

    A J2SE based HttpTransport layer.

    Constructor:

    HttpTransportSE(java.lang.String url)

    Method:

    Return Type Method Description
    void call(java.lang.String SoapAction, SoapEnvelope envelope) set the desired soapAction header field

Step 7

Open your "WebServiceDemo -> src -> WebServiceDemoActivity.java" file and enterr following code:

WebServiceDemoActivity.java

  1. import org.ksoap2.SoapEnvelope;  
  2. import org.ksoap2.serialization.SoapObject;  
  3. import org.ksoap2.serialization.SoapSerializationEnvelope;  
  4. import org.ksoap2.transport.HttpTransportSE;  
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9. import android.widget.EditText;  
  10. import android.widget.Toast;  
  11. public class WebServiceDemoActivity extends Activity  
  12. {  
  13.     /** Called when the activity is first created. */  
  14.     private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";  
  15.     private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";  
  16.     private static String NAMESPACE = "http://tempuri.org/";  
  17.     private static String METHOD_NAME1 = "FahrenheitToCelsius";  
  18.     private static String METHOD_NAME2 = "CelsiusToFahrenheit";  
  19.     private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";  
  20.     Button btnFar,btnCel,btnClear;  
  21.     EditText txtFar,txtCel;  
  22.     @Override  
  23.     public void onCreate(Bundle savedInstanceState)  
  24.     {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.main);  
  27.         btnFar = (Button)findViewById(R.id.btnFar);  
  28.         btnCel = (Button)findViewById(R.id.btnCel);  
  29.         btnClear = (Button)findViewById(R.id.btnClear);  
  30.         txtFar = (EditText)findViewById(R.id.txtFar);  
  31.         txtCel = (EditText)findViewById(R.id.txtCel);  
  32.         btnFar.setOnClickListener(new View.OnClickListener()  
  33.         {  
  34.             @Override  
  35.             public void onClick(View v)  
  36.             {  
  37.                 //Initialize soap request + add parameters  
  38.                 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);  
  39.                 //Use this to add parameters  
  40.                 request.addProperty("Fahrenheit",txtFar.getText().toString());  
  41.                 //Declare the version of the SOAP request  
  42.                 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);  
  43.                 envelope.setOutputSoapObject(request);  
  44.                 envelope.dotNet = true;  
  45.                 try {  
  46.                         HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);  
  47.                         //this is the actual part that will call the webservice  
  48.                         androidHttpTransport.call(SOAP_ACTION1, envelope);  
  49.                         // Get the SoapResult from the envelope body.  
  50.                         SoapObject result = (SoapObject)envelope.bodyIn;  
  51.                         if(result != null)  
  52.                         {  
  53.                               //Get the first property and change the label text  
  54.                               txtCel.setText(result.getProperty(0).toString());  
  55.                         }  
  56.                         else  
  57.                         {  
  58.                               Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();  
  59.                         }  
  60.                   } catch (Exception e) {  
  61.                         e.printStackTrace();  
  62.                   }  
  63.                   }  
  64.   
  65.             });  
  66.         btnCel.setOnClickListener(new View.OnClickListener()  
  67.         {  
  68.             @Override  
  69.             public void onClick(View v)  
  70.             {  
  71.                 //Initialize soap request + add parameters  
  72.                 SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);         
  73.                 //Use this to add parameters  
  74.                 request.addProperty("Celsius",txtCel.getText().toString());  
  75.                 //Declare the version of the SOAP request  
  76.                 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);  
  77.                 envelope.setOutputSoapObject(request);  
  78.                 envelope.dotNet = true;  
  79.                 try {  
  80.                         HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);  
  81.                         //this is the actual part that will call the webservice  
  82.                         androidHttpTransport.call(SOAP_ACTION2, envelope);  
  83.                         // Get the SoapResult from the envelope body.  
  84.                         SoapObject result = (SoapObject)envelope.bodyIn;  
  85.                         if(result != null)  
  86.                         {  
  87.                               //Get the first property and change the label text  
  88.                               txtFar.setText(result.getProperty(0).toString());  
  89.                         }  
  90.                         else  
  91.                         {  
  92.                               Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();  
  93.                         }  
  94.                   } catch (Exception e) {  
  95.                         e.printStackTrace();  
  96.                   }  
  97.                   }  
  98.             });  
  99.         btnClear.setOnClickListener(new View.OnClickListener()  
  100.         {  
  101.             @Override  
  102.             public void onClick(View v)  
  103.             {
  104.                 txtCel.setText("");  
  105.                 txtFar.setText("");  
  106.             }  
  107.         });  
  108.     }  
  109. }  
Step 8

Now, open your "WebServiceDemo -> android.manifest" file. Add the following line before the <application> tag:

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

This will allow the application to use the internet.

Step 9

Run your application in the Android Cell. You will get the following outcome:

Note: In the emulator, we need to fix a proxy, so try the application in an Android Cell.

AndWeb11.jpg

Summary


In this brief tutorial, we learned about Web Services, SOAP envelopes, WSDL files, HTTP transport, and how to use the in an Android application.