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:
- 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.
- 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
[pgsubscribe]
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
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:
- onPreExecute() – Make ProgressBar visible
- doInBackground() – Invoke invokeHelloWorldWS by passing text and webmethod name
- onProgressUpdate() -Does nothing
- 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.
[pglinkadssmall]
If you feel the tutorial is helpful, please share your feedback below.
[pgfeedback]
[pgwriteforus]