How to call Java web service in android

It was bit difficult to find out a good tutorial on how to call Java 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 JEE technology. Before we start with developing application, create a simple web service and deploy it in Apache Tomcat or Glass Fish server (server installed in your local machine or hosted server).

Do follow below link to create and deploy web service using JEE technology in Apache or Glass Fish server:

How-to-create-java-webservice-in-netbeans

Quick Links

Project Structure

Layout creation:

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

Points to note:

  1. Connect your mobile and your local machine (where Apache or Glass Fish server installed) to same WiFi internet connection so that application which we are developing can access WebService installed in the local 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
Subscribe and download free ebook
Email:

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="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:text="Call JEE Webservice"
        android:textSize="30dp" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:singleLine="true" 
        android:hint="Enter you name"/>

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:text="Invoke JEE WS" />

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="" android:textSize="26dp"/>

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:layout_gravity="center_horizontal"
        android:visibility="invisible"
        />

</LinearLayout>

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.android;

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 - can be found in WSDL
	private static String NAMESPACE = "http://example.prgguru.com/";
	//Webservice URL - WSDL File location	
	private static String URL = "http://192.168.1.100:8080/HelloWorldWebService/SayHelloService?WSDL";
	//SOAP Action URI again Namespace + Web method name
	private static String SOAP_ACTION = "http://example.prgguru.com/";
	
	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
		sayHelloPI.setName("name");
		// Set Value
		sayHelloPI.setValue(name);
		// Set dataType
		sayHelloPI.setType(String.class);
		// Add the property to request object
		request.addProperty(sayHelloPI);
		// Create envelope
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		// Set output SOAP object
		envelope.setOutputSoapObject(request);
		// Create HTTP call object
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

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

		} catch (Exception e) {
			//Print error
			e.printStackTrace();
			//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;

onCreate():
Add following code snippet in the place of onCreate method.

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Name Text control
        et = (EditText) findViewById(R.id.editText1);
        //Display Text control
        tv = (TextView) findViewById(R.id.tv_result);
        //Button to trigger web service invocation
        b = (Button) findViewById(R.id.button1);
        //Display progress bar until web service invocation completes
        pg = (ProgressBar) findViewById(R.id.progressBar1);
        //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 
                    task.execute();
                //If text control is empty
                } else {
                    tv.setText("Please enter name");
                }
            }
        });
    }

Class AsyncCallWS:
Create it as inner class inside JavaWSActivity.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> {
		@Override
		protected Void doInBackground(String... params) {
                        //Invoke webservice
			displayText = WebService.invokeHelloWorldWS(editText,"hello");
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			//Set response
			tv.setText(displayText);
                        //Make ProgressBar invisible
			pg.setVisibility(View.INVISIBLE);
		}

		@Override
		protected void onPreExecute() {
                        //Make ProgressBar invisible
			pg.setVisibility(View.VISIBLE);
		}

		@Override
		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" />

Demo

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.

Feedback

If you like this post, please do click 'Appreciate Badge'

*You can "Appreciate" this post only once from this IP


Author: Android Guru

Share This Post On
  • Zyl

    This will be helpful; still have to try it out. Thanks!

  • shiva

    I downloaded the source code and executed the app. Error is occuring

    • http://android.programmerguru.com/ Android Guru

      @disqus_PEBx4m7FRz:disqus,

      Can you post error message here so that I can help you?

  • Edwin

    Thanks for tutorial!
    I’ve build an application but i would extend my application to use complextype and arrays from JEE Web services, can you help me with simple tutorials or examples?

  • neliel

    This is such a nice tutorial.
    Just to add, how are you going to handle cases where the web service soap endpoint requires authentication mechanism such as simple user name and password?

  • Priyanka

    Hi friend.
    thanks for your blog & very helpful

    how to call if web service in localhost & PC in offline mode

    I mean if web service url = “http://localhost…..?wsdl”

    then its not called.when i connect this to internet then get IP address and replace url like this then its works

    url = “http://119.235.10.55/…..?wsdl”

  • Ambar

    Languages

    Video Tutorials Collection

  • Dinesh M K

    Hi,

    Thanks for the tutorial.

    I have developed a webservice project for the above example and while working I got the following error.

    FATAL EXCEPTION: AsyncTask #4
    java.lang.RuntimeException: An error occured while executing doInBackground()
    at android.os.AsyncTask$3.done(AsyncTask.java:299)
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    at java.lang.Thread.run(Thread.java:856)
    Caused by: java.lang.StackOverflowError
    at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:147)
    at java.lang.StringBuffer.append(StringBuffer.java:219)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:215)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.append(StringBuffer.java:203)
    at org.ksoap2.serialization.PropertyInfo.toString(PropertyInfo.java:219)
    at java.lang.StringBuffer.

    Can you please send me the webservice samples aslo.

    Thanks once again.

  • Jagan

    Thanks for wonderful tutorial! :)

    • http://android.programmerguru.com Android Guru

      Welcome Jagan! :)

      • Niranjan

        Hello Sir I need the we services class of this project

x
Subscribe and stay in touch!!

Enter your email and stay on top of things:

Your email address will not be published