Hello web service with name as the request argument is output on an Android virtual device emulator.--> Pre-requisites
The article assumes prior knowledge of web services. We shall create a simple JAX-WS web service with a method that takes a name as an argument and returns a Hello greeting. To develop a web service we would need the following software frameworks.
- Eclipse IDE
- An application server that supports JAX-WS web services. For a beginner tutorial on developing a JAX-WS web service with WebSphere refer Resources.
- Eclipse IDE
- Android SDK
- ADT Plugin for Eclipse
- KSoap2-android library
A JAX-WS web service essentially consists of a Java class annotated with the
javax.jws.WebService
annotation, the web service endpoint. A web service may optionally
consist of a service endpoint interface that is implemented by the
service endpoint implementation class. A web service implementation
class must not be abstract or final. Business methods of the implementation class that are to be exposed as operations to a web service client must be public, and must not be static or final. Create a web service implementation class HelloWSImpl, which is annotated with the @WebService annotation and implements the HelloWS interface. The implementation class contains a method hello that takes a String parameter for name and returns a Hello message containing the name. The implementation class is listed in Listing 1.
Listing 1. Web Service Implementation Class HelloWSImpl.java
package hello_webservice;
import javax.jws.*;
@WebService(portName = "HelloWSPort", serviceName = "HelloWSService",
targetNamespace = "http://hello_webservice/",
endpointInterface = "hello_webservice.HelloWS")
public class HelloWSImpl implements HelloWS {
public String hello(String name) {
// replace with your impl here
return "Hello "+name +" Welcome to Web Services!";
}
}
|
The service endpoint interface
HelloWS contains the hello method annotated with the @WebMethod annotation and is listed in Listing 2. Listing 2. Service Endpoint Interface HelloWS.java
package hello_webservice;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService(name = "HelloWS", targetNamespace =
"http://hello_webservice/")
public interface HelloWS {
@WebMethod(operationName = "hello")
public String hello(String name);
}
|
Next, generate a WSDL for the web service. The web service shall be made available to an Android client as a WSDL. A WSDL is a document in XML format for describing a web service as a collection of network endpoints, which are also called ports. Messages are abstract definitions of the data being exchanged, and port types are an abstract collections of operations. The Design view of the WSDL for the
HelloWSService web service is shown in Figure 1. Figure 1. Design View of the WSDL
The WSDL for the web service is shown in Figure 2.
Figure 2. Web service WSDL
Installing the ADT Eclipse Plugin & SDK
The Android Development Tools (ADT) is a plugin for Eclipse IDE that provides an integrated environment for developing Android applications. Android SDK provides tools and libraries to develop Android applications. To install the ADT Plugin, select Help>Install New Software... Click on Add. In Add Repository specify a Name and specify Location as
https://dl-ssl.google.com/android/eclipse/ as shown in Figure 3. Click on OK. Figure 3. Creating a Repository for ADT Plugin
Select the Developer Tools listed as shown in Figure 4. and click on Next.
Figure 4. Installing Developer Tools
Click on Next in Install Details. Accept the terms of the license agreements and click on Finish. The ADT Plugin gets installed. Next, install the Android SDK. Download the Android starter package (
installer_r09-windows.exe
for Windows). Click on the installer to start the Android SDK Tools
Setup Wizard. The JDK is required to install the Android SDK; install
JDK 5.0/6.0 if not already installed. Click on Next. Specify the Install
Location (C:\Program Files\Android\android-sdk-windows is
the default) and click on Next. Choose a Start Menu Folder and click on
Install. The Android SDK Tools gets installed as shown in Figure 5.
Click on Next. Figure 5. Installing Android SDK Tools
Click on Finish. The Android SDK and AVD Manager gets started. Select packages to install from Available Packages. Install the packages shown in Figure 6.
Figure 6. Android SDK and AVD Manager
Next, configure the Preferences for Android. Select Window > Preferences in Eclipse. In Preferences select the Android node. Specify the SDK Location as shown in Figure 7.
Figure 7. Setting Android SDK Location
Creating an Android project
Next, create an Android project in which we shall create the web service client for Android. In Eclipse IDE select File > New. In New select Android>Android Project as shown in Figure 8. Click on Next.
Figure 8. New Android project
In New Android Project specify a Project name (
AndroidWSClient).
For Build Target select Android 2.2. In Properties specify an
Application name, and a package name. Select the checkbox Create
Activity and specify the Activity class (AndroidWSClient).
An activity represents a user interaction and the class extending the
Activity class creates a window for a UI. Specify the minimum SDK
version as 8 and click on Next as shown in Figure 9. Figure 9. Creating a new Android project
In New Android Test Project a Test Project may be created. We won't be creating a test project. Click on Finish. An Android project gets created as shown in Figure 10. The Android project consists of the following essential components.
- An activity class(
AndroidWSClient), which extends the Activity class. - A
res/layout/main.xmlfile to specify the layout of the Android application. - An
AndroidManifest.xmlfile, which contains essential information about the application such as the package name, application components, processes, permissions, and the minimum API level for the Android system.
Figure 10. Android project
Installing the Ksoap2-android library
The Ksoap2-android library is a lightweight and efficient SOAP library for the Android platform. Download
ksoap2-android-assembly-2.4-jar-with-dependencies.jar
from ksoap2-android project. Add the Ksoap2-android assembly JAR, which
includes the dependencies to the Java Build Path as shown in Figure 11.
Figure 11. The Ksoap2-android Library
Creating the layout
In the
res/layout/main.xml specify the layout of the
Android UI components. We shall create a UI in which the response from
the web service is displayed as a text message. Create a LinearLayout in which sub-elements are displayed in a linear layout, vertically. Add a TextView element, with id result, to display the web service response for a method call to the hello method. The method invocation sends a name as an argument and gets a Hello message as a response. Optionally, create a TextView
element for a title. The Graphical Layout of the Android web
service-client application is shown in Figure 12. The Android screen is
essentially blank with a provision to display a web service response as a
text message. Figure 12. The Graphical Layout
The
main.xml layout file is listed in Listing 3.Listing 3. Layout file main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="" /> <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> |
Creating the Activity Class
The
AndroidWSClient class is the activity class of an Android application and extends the Activity class. In this section we shall construct the AndroidWSClient activity class. Import the required Ksoap2-android classes: import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import org.ksoap2.serialization.PropertyInfo; |
Define constants discussed in Table 1.
Table 1. Constants in Activity Class
| Constant | Description |
|---|---|
| NAMESPACE | Namespace is the targetNamespace in the WSDL. |
| URL | The WSDL URL. Its value is the location attribute of the soap:address element for a port element in a WSDL. Unless the web service is also hosted on the Android device, the hostname should not be specified as localhost, because the application runs on the Android device while the web service is hosted on the localhost server. Specify hostname as the IP address of the server hosting the web service. |
| METHOD_NAME | The name of the web service operation, which may be obtained form the WSDL. |
| SOAP_ACTION | NAMESPACE+METHOD_NAME specified as a String literal. |
private static final String NAMESPACE = "http://hello_webservice/"; private static String URL="http://192.168.1.68:7001/HelloWebService/HelloWSService?WSDL"; private static final String METHOD_NAME = "hello"; private static final String SOAP_ACTION = "http://hello_webservice/hello"; |
All Activities must implement the
onCreate method for activity initialization. Define the UI using the setContentView method and the layout resource. setContentView(R.layout.main); |
Create an Android widget
TextView object using the findViewById method on the TextView element defined in the main.xml.TextView lblResult = (TextView) findViewById(R.id.result); |
Create a
org.ksoap2.serialization.SoapObject object to build a SOAP request. Specify the namespace of the SOAP object and method name to be invoked in the SoapObject constructor.SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); |
Create a
org.ksoap2.serialization.PropertyInfo object to contain property information to be sent with the SOAP method call. Each property requires a new PropertyInfo object. The hello method takes only 1 argument for a name. Set the property name as "arg0", and specify the type of the property as STRING_CLASS. Add the PropertyInfo object to the SoapObject using the addProperty method.PropertyInfo propInfo=new PropertyInfo(); propInfo.name="arg0"; propInfo.type=PropertyInfo.STRING_CLASS; request.addProperty(propInfo, "John Smith"); |
Next create a SOAP envelop. Use the
SoapSerializationEnvelope class, which extends the SoapEnvelop
class, with support for SOAP Serialization format, which represents the
structure of a SOAP serialized message. The main advantage of SOAP
serialization is portability. SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); |
The constant
SoapEnvelope.VER11 indicates SOAP Version 1.1. Assign the SoapObject request object to the envelop as the outbound message for the SOAP method call. envelope.setOutputSoapObject(request); |
Create a
org.ksoap2.transport.HttpTransportSE object that represents a J2SE based HttpTransport layer. HttpTransportSE extends the org.ksoap2.transport.Transport class, which encapsulates the serialization and deserialization of SOAP messages. HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); |
Make the soap call using the
SOAP_ACTION and the soap envelop. androidHttpTransport.call(SOAP_ACTION, envelope); |
Get the web service response using the
getResponse method of the SoapSerializationEnvelope object and cast the response object to SoapPrimitive, class used to encapsulate primitive types. SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse(); |
Set the String message in the SOAP response in the
TextView UI component.lblResult.setText(resultsRequestSOAP.toString()); |
The
Activity class is listed below in Listing 4.
Listing 4. Activity Class AndroidWSClient.java
package android.webservice.client;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.serialization.PropertyInfo;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class AndroidWSClient extends Activity {
private static final String NAMESPACE = "http://hello_webservice/";
private static String URL = "http://192.168.1.68:7001/HelloWebService/
HelloWSService?WSDL";
private static final String METHOD_NAME = "hello";
private static final String SOAP_ACTION = "http://hello_webservice/hello";
private TextView lblResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lblResult = (TextView) findViewById(R.id.result);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo propInfo=new PropertyInfo();
propInfo.name="arg0";
propInfo.type=PropertyInfo.STRING_CLASS;
request.addProperty(propInfo, "John Smith");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
lblResult.setText(resultsRequestSOAP.toString());
} catch (Exception e) {
}
}
}
|
Configuring Internet Access Permission
To access a web service from an Android device we need to enable a permission in
AndroidManifest.xml that allows applications to open network sockets. Add the following uses-permission element.<uses-permission android:name="android.permission.INTERNET"></uses-permission> |
The
AndroidManifest.xml with the permission set is shown in Figure 13. Figure 13. Setting the INTERNET Permission
The
AndroidManifest.xml is listed in Listing 5. Listing 5. AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.webservice.client"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidWSClient"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-sdk android:minSdkVersion="8" />
</manifest>
</uses-permission>
|
Creating an AVD
Android SDK provides a mobile device emulator, a virtual mobile device to develop and test Android applications. The emulator supports Android Virtual Device (AVD) configurations with which other virtual mobile device options such as Android platform may be specified. To create an AVD click on Window>Android SDK and AVD Manager. Click on Virtual devices and click on New as shown in Figure 14.
Figure 14. Creating an AVD
In Create New AVD specify a Name, select Target as Android 2.2-API level 8. Specify SD Card size as 100 MiB, which should be sufficient to install the web client application. Specifying a lower value such as 10 may generate a "No space left on device" error. Click on Create AVD to create an AVD as shown in Figure 15.
Figure 15. Configuring AVD
A new AVD get created as shown in Figure 16.
Figure 16. New AVD
Running the Android Client to access the web service
The Android emulator provides various options to customize the emulator. For example, to scale the emulator specify the
scale value with the following option.-scale <value> |
To specify an emulator option right-click on the
AndroidWSClient application and select Run As..>Run Configurations. Select the AndroidWSClient application and specify the -scale option in field Additional Emulator Command Line Options and click on Apply as shown in Figure 17.
Figure 17. Setting the Emulator scale Option
To install and run the
AndroidWSClient application on the emulator right-click on AndroidWSClient and select Run As..>Android Application as shown in Figure 18. Figure 18. Running the Android Application
The
AndroidWSClient application gets installed on
the AVD as shown in Figure 19. Click on the application to run the web
service client in the AVD. Figure 19. Android web service client installed
The web service gets invoked and the response from the web service gets displayed in the Android emulator as shown in Figure 20.
Figure 20. Accessing the web service
The output from the running the Android application is shown in Listing 6.
Listing 6. Output from Android Application
AndroidWSClient] Android Launch!
AndroidWSClient] adb is running normally.
AndroidWSClient] Performing android.webservice.client.AndroidWSClient activity launch
AndroidWSClient] Automatic Target Mode: launching new emulator with compatible AVD
'AndroidAVD'
AndroidWSClient] Launching a new emulator with Virtual Device 'AndroidAVD'
AndroidWSClient] New emulator found: emulator-5554
AndroidWSClient] Waiting for HOME ('android.process.acore') to be launched...
AndroidWSClient] HOME is up on device 'emulator-5554'
AndroidWSClient] Uploading AndroidWSClient.apk onto device 'emulator-5554'
AndroidWSClient] Installing AndroidWSClient.apk...
AndroidWSClient] Success!
AndroidWSClient] Starting activity android.webservice.client.AndroidWSClient on device
emulator-5554
AndroidWSClient] ActivityManager: Starting: Intent { act=android.intent.action.MAIN
cat=[android.intent.category.LAUNCHER]
cmp=android.webservice.client/.AndroidWSClient }
|
When the Android application is run the following tasks are performed.
- A new emulator gets launched
- The
AndroidWSClient.apkgets uploaded to the emulator - The
AndroidWSClient.apkgets installed - The
android.webservice.client.AndroidWSClientactivity gets started
Resources
Learn
- Learn about Android. Tools and documentation on how to create Android applications.
- In the SOA and web services zone on developerWorks, get the project resources you need to advance your web services skills.
- ""Develop and deploy JAX-WS Web services on WebSphere Application Server Community Edition V2.0" (developerWorks, Sept 2007) as a tutorial on developing and deploying JAX-WS web services with WebSphere application server.
Enregistrer un commentaire