Home > Android, Java > How to call a web service from Android

How to call a web service from Android

By far the easiest way is to use the ksoap2-android API. You need the ksoap2 jar file (with all dependencies) which can be found here and you need to add this to your classpath. In the following sample code we call a free web service, called currency convertor, which has one operation (method) that is is called ConversionRate. If you look at the service dscription (the WSDL file), you will see that this operation takes two parameters, FromCurrency and ToCurrency. Lets say that we want to find out the conversion rate from USD to EUR. We implement the following Activity

package gr.panos.caller;

import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class ConvertorCaller extends Activity {

	public final static String URL = "http://www.webservicex.net/CurrencyConvertor.asmx";
	public static final String NAMESPACE = "http://www.webserviceX.NET/";
	public static final String SOAP_ACTION = "http://www.webserviceX.NET/ConversionRate";
	private static final String METHOD = "ConversionRate";
	private TextView textView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_convertor_caller);
		textView = (TextView) findViewById(R.id.textView1);
		AsyncTaskRunner runner = new AsyncTaskRunner();
		runner.execute();
	}

	 private class AsyncTaskRunner extends AsyncTask<String, String, String>{

		 private String resp;

		@Override
		protected String doInBackground(String... params) {
		     try {
		      SoapObject request = new SoapObject(NAMESPACE, METHOD);
		      request.addProperty("FromCurrency", "USD");
		      request.addProperty("ToCurrency", "EUR");

		      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		      envelope.dotNet = true;
		      envelope.setOutputSoapObject(request);  
		      System.out.println("************ I AM SENDING: " + envelope.bodyOut);
		      
		       HttpTransportSE transport = new HttpTransportSE(URL);
		       try {
		         transport.call(SOAP_ACTION, envelope);
		       } catch (IOException e) {
		         e.printStackTrace();
		       } catch (XmlPullParserException e) {
		         e.printStackTrace();
		     }
		   if (envelope.bodyIn != null) {
			   if (envelope.bodyIn instanceof SoapFault) {
				   String s = ((SoapFault) envelope.bodyIn).faultstring;
				   System.out.println("************ ERROR: " + s);
				   resp = s;
			   } else if (envelope.bodyIn instanceof SoapObject) {
				   SoapObject obj = ((SoapObject) envelope.bodyIn); 
				   System.out.println("**** RESPONSE: " +obj);
				   
				   SoapPrimitive root = (SoapPrimitive) obj.getProperty(0);
				   System.out.println("**** CONVERSION RATE: " +root.toString());
				   
				   resp = root.toString();
			   }
				   
		   }
		 } catch (Exception e) {
		   e.printStackTrace();
		   resp = e.getMessage();
		 }
	     return resp;
	   }

		  /**
		   * 
		   * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		   */
		  @Override
		  protected void onPostExecute(String result) {
			  textView.setText(resp);
		  }
	
		  /**
		   * 
		   * @see android.os.AsyncTask#onPreExecute()
		   */
		  @Override
		  protected void onPreExecute() {
		  }
		  /**
		   * 
		   * @see android.os.AsyncTask#onProgressUpdate(Progress[])
		   */
		  @Override
		  protected void onProgressUpdate(String... text) {
		  }
	}

}

You also need to define a text view in your layout as well as give the activity INTERNET permission in your manifest file.

Advertisements
  1. 31 July 2015 at 12:55 pm

    Thanks for this post, it is very useful. I will use it in my next project.

  1. No trackbacks yet.

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

%d bloggers like this: