Monday, May 29, 2017

Know How to Consuming SOAP(asmx) Web Service through Android

This article will help you call a SOAP web service in the simplest way. We will pass a parameter to the web service an will receive it's result. In this tutorial I have used w3school's TempConvert web service. It's publicly available to everyone to consume the web service.

Before we begin with the code, we would to have download KSOAP library for our android project. The library used in this article is ksoap2-android-assembly-2.6.1-jar-with-dependencies.jar. To include this library in your project - Right Click on the project> Select Properties> Java Build Path> Libraries Tab> Add External JARs and then select your downloaded library. Now, on the Order and Export Tab checkmark the checkbox for this library.

The web service has two methods i.e CelsiusToFahrenheit and FahrenheitToCelsius so we have to design a simple android activity for the same.

Layout - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TempConvert"
        android:layout_gravity="center"
        android:layout_marginBottom="20dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Input:" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:layout_marginBottom="5dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert To:" />

    <RadioGroup android:id="@+id/rgTemp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    
    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Celsius" />

    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dp"        
        android:text="Fahrenheit" />
    
    </RadioGroup>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result:" />

   <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:editable="false"
        android:ems="10" />

</LinearLayout>
 

To make a call to a SOAP web service, we mainly need four variables i.e namespace, method_name, address and soap_action. Here's how to get them.  


Now, we have to pass the parameter to web to get the result. We use the PropertyInfo class of the KSOAP library to pass the value and it's description.
PropertyInfo pi=new PropertyInfo();
pi.setName(PROPERTY_NAME);
pi.setValue(val);
pi.setType(String.class);
request.addProperty(pi);

We have set a setOnCheckedChangeListener on our radio group. So, whenever user selects an option we will take the value from the input edittext and then call our function which will pass the user input to the web service. Also, if user selects convert to Fahrenheit(or vice-versa) that means he has entered a Celsius value wants to convert it to Fahrenheit. Hence, we will call CelsiusToFahrenheit method of the web service and change variables accordingly.

Here's is the whole code-

package com.loginworks.demo;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class SOAPDemoActivity extends Activity {
    EditText input,result;
    RadioButton cel,fah;
    RadioGroup rGroup;
    String PROPERTY_NAME;
    
    public  String SOAP_ACTION;

    public  String METHOD_NAME; 

    public  final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

    public  final String SOAP_ADDRESS = "http://www.w3schools.com/webservices/tempconvert.asmx";
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        input = (EditText) findViewById(R.id.editText1);
        result = (EditText) findViewById(R.id.editText2);
        
        cel= (RadioButton) findViewById(R.id.radioButton1);
        fah= (RadioButton) findViewById(R.id.radioButton2);
        
        rGroup = (RadioGroup) findViewById(R.id.rgTemp);
        

       rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()  {
            public void onCheckedChanged(RadioGroup rGroup, int checkedId)  {
                
            String in = input.getText().toString();
            
               if (cel.isChecked()) {
                   PROPERTY_NAME = "Fahrenheit";
                   METHOD_NAME = "FahrenheitToCelsius";
                   SOAP_ACTION  = "http://tempuri.org/FahrenheitToCelsius";                   
               }
               else {
                   PROPERTY_NAME = "Celsius";
                   METHOD_NAME = "CelsiusToFahrenheit";
                   SOAP_ACTION  = "http://tempuri.org/CelsiusToFahrenheit";
               }
                                           
               Convert(in);
               
            }            
        });        
      }   
    
    public void Convert(String val) {
         SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, METHOD_NAME);
         
         PropertyInfo pi=new PropertyInfo();

             pi.setName(PROPERTY_NAME);
                pi.setValue(val);
                pi.setType(String.class);
                request.addProperty(pi);
                         
             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
             envelope.dotNet = true;

             envelope.setOutputSoapObject(request);

             HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);

             Object response= null;
             
             try    {
                 
             httpTransport.call(SOAP_ACTION, envelope);
             response = envelope.getResponse();

                 }
             catch (Exception exception) {   
                 
                 response=exception;                     
                 }
                 
             result.setText(response.toString());
    }
}



Note: When you will select an option, you would notice that your activity gets stuck for few seconds that is because we are working with network on the UI thread. So, it's advisable to create a new thread or AsyncTask for network related functions.
Also, don't forget to register your Activity in your Manifest file and add the following permission
<uses-permission android:name="android.permission.INTERNET" />



 

1 comment: