How to call web service in android

It was bit difficult to find out a good tutorial on how to call ASP .Net web service from inside Android application so I just decided to write one.

In this post, we are going to discuss about calling a web service from inside an Android application that has been developed using ASP .Net technology.

Before we start with developing application, create a simple web service and deploy it in IIS server (server installed in your local machine or hosted server).

Do follow below links to create and deploy web service using ASP .Net in IIS server:


Quick Links

Project Structure

Layout creation:

  • Create new android project [File >> New >> Android Project] with project name DotNetWSActivity
  • Click next and select target android device version [I chose version 3.2]
  • Click next and enter package name – ‘’
  • Click finish

Points to note:

  1. Connect your mobile and your local machine (where IIS installed) to same WiFi internet connection so that application which we are developing can access WebService installed in the local IIS server.
  2. Make sure you turned off Firewall in your local machine since FireWall will not allow the local machine to accept Http calls from other machines or servers


As this application requires Internet connectivity to hit Web Service hosted in remote server, it would be good if Internet connectivity check is done before trying to hit Web Service.

Here are the tutorials which talk about checking Wifi/Mobile Internet:

Android Check Wi-Fi Internet Connection
Android Check Mobile Internet Connection

KSOAP client library is being used in Android to make WebService calls. You can download KSOAP library from here and add it in lib folder of Android project

Code Listings

Layout XML:

Open main.xml present under /res/layout folder and replace the XML with the below one.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:text="Call .Net Webservice"
        android:textSize="30dp" />

        android:hint="Enter you name"/>

        android:text="Invoke .Net WS" />

        android:text="" android:textSize="26dp"/>



Application layout will look like:

Change to graphical layout of Main.xml, the layout design should look like below:

Create a new class called ‘WebService’ which is going to have basic webservice configuration and web method invocations:

package com.prgguru.example;

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;

public class WebService {
	//Namespace of the Webservice - It is for .NET webservice
	private static String NAMESPACE = "";
	//Webservice URL - It is asmx file location hosted in the server in case of .Net
        //Change the IP address to your machine IP address	
	private static String URL = "";
	//SOAP Action URI again
	private static String SOAP_ACTION = "";

	public static String invokeHelloWorldWS(String name, String webMethName) {
		String resTxt = null;
		// Create request
		SoapObject request = new SoapObject(NAMESPACE, webMethName);
		// Property which holds input parameters
		PropertyInfo sayHelloPI = new PropertyInfo();
		// Set Name
		// Set Value
		// Set dataType
		// Add the property to request object
		// Create envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
		//Set envelope as dotNet
		envelope.dotNet = true;
		// Set output SOAP object
		// Create HTTP call object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

		try {
			// Invoke web service, envelope);
			// Get the response
			SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
			// Assign it to resTxt variable static variable
			resTxt = response.toString();

		} catch (Exception e) {
			//Print error
			//Assign error message to resTxt
			resTxt = "Error occured";
		//Return resTxt to calling object
		return resTxt;

Create following objects under DotNetWSActivity class:

	Button b;
	TextView tv;
	EditText et;
	ProgressBar pg;
	String editText;
	String displayText;

Add following code snippet in the place of onCreate method.

 public void onCreate(Bundle savedInstanceState) {
        //Name Text control
        et = (EditText) findViewById(;
        //Display Text control
        tv = (TextView) findViewById(;
        //Button to trigger web service invocation
        b = (Button) findViewById(;
        //Display progress bar until web service invocation completes
        pg = (ProgressBar) findViewById(;
        //Button Click Listener
        b.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Check if Name text control is not empty
                if (et.getText().length() != 0 && et.getText().toString() != "") {
                    //Get the text control value
                	editText = et.getText().toString();
                    //Create instance for AsyncCallWS
                    AsyncCallWS task = new AsyncCallWS();
                    //Call execute 
                //If text control is empty
                } else {
                    tv.setText("Please enter name");

Class AsyncCallWS:
Create it as inner class inside DotNetWSActivity.class.
This class will perform the webservice call which will be executed as separate thread. When execute method is called in onCreate method, it calls the following methods in order:

  1. onPreExecute() – Make ProgressBar visible
  2. doInBackground() – Invoke invokeHelloWorldWS by passing text and webmethod name
  3. onProgressUpdate() -Does nothing
  4. onPostExecute() – Make ProgressBar invisible and set the webservice response text in TextView
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
		protected Void doInBackground(String... params) {
                        //Invoke webservice
			displayText = WebService.invokeHelloWorldWS(editText,"sayHello");
			return null;

		protected void onPostExecute(Void result) {
			//Set response
                        //Make ProgressBar invisible

		protected void onPreExecute() {
                        //Make ProgressBar invisible

		protected void onProgressUpdate(Void... values) {


Click here to know more about AsyncTask,

Internet permission
Don’t forget to add internet permission in AndroidManifest.xml:

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



Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screens:

Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.


If you feel the tutorial is helpful, please share your feedback below.


Related Articles

Author: Udhay

Share This Post On
468 ad
  • inf

    very useful post bro…

  • dadung

    Hi, thank you for your tutorial.
    I have one problem when following your tutorial
    Specifically, I followed your previous tutorials to set up web service successfully.
    But when I follow your above tutorial and implement Android client, the result is always “Error occured”.
    I replace the address of web service by other address given here ( and my client can access to this web service
    I am also turn off all fire walls in my computer.
    Could you please help me to solve this problem.
    Thank you so much!

    • Could you check your log message and let me know what error are you seeing there so that I can help you?

  • Do Loan

    I did do follow guide but I don’t load services on server. help me!

  • Amila Thennakoon

    This works for me ….. how to send double parameter insted of String parameters

    • You have to just set the Type of PropertyInfo as ‘Double.class’ in the place of ‘String.class’.

      • Amila Thennakoon

        its not work ….

        • Have you created web service and deployed it in local server?
          Please let us know at which point you are stuck so that we will try to help you.

  • thomas

    excellent article, explained well and it works

    • Thanks Thomas!

      • thomas

        I tried to display a list view based on an arraylist (populated from sql server at webservice) that gives me error at postExecute() arraylist has current values. What could be the reason? Any suggestions?


        protected Void doInBackground(String… params) {

        //displayText = WebService.invokeHelloWorldWS(editText,”GetMenuList”);

        arraylist = WebService.invokeHelloWorldWS(editText,”GetMenuList”);

        return null;



        protected void onPostExecute(Void result) {

        //tv.setText(fahren + “° F”);


        list.setAdapter(new ArrayAdapter(DotNetWSActivity.this,

        android.R.layout.simple_list_item_1, arraylist));



      • thomas

        please ignore the question I sent earlier, fixed it, some silly comment out was the issue, thanks

  • Arvind Kumar

    I created a webservice as per “How to create webservice in using csharp” and using Visual Studio 2012 ran it on my localhost

    then I downloaded the source code for “How to call web service in android”, and imported it in eclipse ADT IDE

    after making changes in for ipaddress. I ran it.

    The screen to “Call .Net Webservice” showed up but when I entered a name and clicked button “Invoke .Net WS” it showed “Error Occured”

    I am unable to figure out what is the issue. Can someone suggest me?

    PS: I am using Samsung 4.1.2 Galaxy Tablet.

    • Please see logcat for what error or exception has occurred.

      Do post the error message so that I can help you out.

  • saan

    i try your code but i have error when run your code.

    • Hi Saan,

      Can you please post the error message you are getting here so that will take a look at it and help you out?

  • js

    hey,its a very helpful article

    But i am getting “Error occured” evrytime

    and Log =

    05-10 16:49:49.200: E/SpannableStringBuilder(32668): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

    05-10 16:49:49.210: E/SpannableStringBuilder(32668): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length

    05-10 16:49:49.741: D/GestureDetector(32668): [Surface Touch Event] mSweepDown False, mLRSDCnt : -1 mTouchCnt : 4 mFalseSizeCnt:0

    05-10 16:50:03.754: W/System.err(32668): org.xmlpull.v1.XmlPullParserException: expected: START_TAG {}Envelope (position:START_TAG @2:44 in

    05-10 16:50:03.764: W/System.err(32668): at

    05-10 16:50:03.764: W/System.err(32668): at org.ksoap2.SoapEnvelope.parse(

    05-10 16:50:03.764: W/System.err(32668): at org.ksoap2.transport.Transport.parseResponse(

    05-10 16:50:03.764: W/System.err(32668): at

    05-10 16:50:03.764: W/System.err(32668): at com.example.webservice.WebService.invokeHelloWorldWS(

    05-10 16:50:03.764: W/System.err(32668): at com.example.webservice.Main$AsyncCallWS.doInBackground(

    05-10 16:50:03.764: W/System.err(32668): at com.example.webservice.Main$AsyncCallWS.doInBackground(

    05-10 16:50:03.764: W/System.err(32668): at android.os.AsyncTask$

    05-10 16:50:03.764: W/System.err(32668): at

    05-10 16:50:03.764: W/System.err(32668): at android.os.AsyncTask$SerialExecutor$

    05-10 16:50:03.764: W/System.err(32668): at java.util.concurrent.ThreadPoolExecutor.runWorker(

    05-10 16:50:03.764: W/System.err(32668): at java.util.concurrent.ThreadPoolExecutor$

    05-10 16:50:03.764: W/System.err(32668): at

  • Try to use native Android keyboard to enter values to your Application. The error is more of related to the keyboard you are using.

    Take a look at this discussion:

  • Maicol

    Excellent article, I need a tuto please… about how to connect android with oracle using soap.. I am new in WS.. please help me… And Guru your tutorials are the best in the internet… if somebody know help me please.. my e-mail is please @programmerguru:disqus

  • Thanks for your feedback. Please follow this link for Webservice tutorials.

  • Kim

    I followed your tutorial but I get error when casting envelope.getResponse() to SoapPrimitive
    Error: “.

    java.lang.ClassCastException: org.ksoap2.serialization.SoapObject cannot be cast to org.ksoap2.serialization.SoapPrimitive”

  • Hemal

    Hello Android Guru: Thanks for such wonderful tutorial. For me earlier I tried static String URL with “localhost” that was causing problem but after I put my ip. It worked and changed




    And it showed desired result.

    Thank you.

  • Cool 🙂

    • Ive done this change but in vain
      Its giving only Hello without the provided name


    unfortunately app has stoped

  • Did you create ASP Dot Net webservice? Make sure it is up and running fine so that Application can invoke it.

    Go through the logcat log message to fix the issue.


    all the things looking fine but the result is not showing

  • Boris Soto

    Very useful, thanks master

  • Make sure your device and server are connected to same WiFi connection.

  • prachi mittal

    thanku for the useful tutorial.

    but everytime i m getting ‘Error Occured’

    logcat: failed to connect to / (port 50681): connect failed: ETIMEDOUT (Connection timed out)

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest