Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

13/10/2015 The Droid Chronicles – Web Services: kSOAP2-Based Solutions

roderickbarnes.com http://roderickbarnes.com/droid-chronicles-web-services-part-1/

The Droid Chronicles – Web Services: kSOAP2-Based


Solutions
Roderick L. Barnes, Sr.

Why has Google forsaken us? To be sure, they have provided a plethora of great
technologies and accoutering for productivity. But when it comes to enabling
software developers in the work of creating Android clients for web services…
we have been abandoned. Okay, enough with the melodramatic ranting. That is
not what you came to this site for. If your are a Google fanboy you need not
worry about this being a bashing post. I really like the work that has been done
by the software giant for the developer community. But I will not pretend to see
the wisdom in leaving the web services APIs out of the port of Java to Android.
(There are a few Java APIs that would really be appreciated by the Android
android logo (Roderick L.
developer community. E.g., javax.naming.*) What the heck? But there is hope. In Barnes, Sr. – The Droid
this series of blog posts I will show you two viable options for building Android- Chronicles)

based web service clients. In this particular example I will create a simple web
service using the standard Java 6 SDK and then create a kSOAP2 client for that service. In the next post we
will create a wsclient-based client for the same service. By the end of this tutorial you will be better equipped
to

Understand creating web services using the simple provisions of the Java 6 SDK
Create a web service client using the kSOAP2 library. This library has been around for a while and
there are quite a few good tutorials on how to use it. This one will not break new ground but will help
you compare and contrast creating clients using competing technologies
Create a web service using the WSClient++ library. It is produced by a company named
Neurospeech. I believe it provides a simple and robust solution for developers.

Read on and have fun!

A Simple Web Service


http://roderickbarnes.com/droid-chronicles-web-services-part-1/ 1/6
13/10/2015 The Droid Chronicles – Web Services: kSOAP2-Based Solutions

The following code snippets come together to provide a web service that can be used for the remaining
discussion. I have kept them simple so as to not bog down the discussion or create unnecessary digressions
with the coolness of the service. It is the time-honored programming example HelloWorld. The first class is
the service endpoint interface (SEI):

01 package com.bif;
02
03 import javax.jws.WebMethod;
04 import javax.jws.WebService;
05 import javax.jws.soap.SOAPBinding;
06 import javax.jws.soap.SOAPBinding.Style;
07
08 /**
09 * This interface is the contract for any class that would
10 * provide an implementation of the greeting service.
11 * @author <a href="mailto:roderick@biftechnologies.com">roderick.barnes</a>
12 */
13
14 @WebService
15 @SOAPBinding(style = Style.RPC)
16 public interface GreetingService {
17 /**
18 * Should return the standard "Hello, world!" greeting.
19 * @return the standard "Hello, world!" greeting.
20 */
21 @WebMethod String getGreeting();
22
23 /**
24 * Provides a customized greeting based on the given name
25 (<code>stringName</code>).
26 * @param stringName name supplied by the calling program to be
27 * used in the greeting.
28 * @return a greeting that includes the name that was supplied.
29 */
30 @WebMethod String getGreetingForName(String stringName);
}

After specifying the interface we can specify the implementation; this is the service implementation bean
(SIB). Note: Although you can do all of this in one class it is better to separate the definition of the type from
the implementation.

01 package com.bif;
02
03 import javax.jws.WebService;
04
05 import java.text.SimpleDateFormat;
06 import java.util.GregorianCalendar;

http://roderickbarnes.com/droid-chronicles-web-services-part-1/ 2/6
13/10/2015 The Droid Chronicles – Web Services: kSOAP2-Based Solutions

07
08 @WebService(endpointInterface = "com.bif.GreetingService")
09 public class GreetingServiceImplementation implements GreetingService {
10 @Override
11 public String getGreeting() {
12 GregorianCalendar gregorianCalendar = new GregorianCalendar();
13 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd
14 hh:mm:ss");
15 String stringResponseTimestamp =
16 simpleDateFormat.format(gregorianCalendar.getTime());
17 return "Hello, world! - " + stringResponseTimestamp;
18 }
19
20 @Override
21 public String getGreetingForName(String stringName) {
22 return "Hello, " + stringName + "!";
}
}

Finally, we need to publish the service. In the following block of code we leverage the Endpointpublisher to
deliver web services to clients. It is okay for simple testing but cannot be used to meet the demanding needs
of a production environment; the version shown below will only handle one client request at a time.

01 package com.bif;
02
03 import javax.xml.ws.Endpoint;
04
05 public class GreetingServicePublisher {
06 public static void main(String[] arrayOfString) throws Exception {
07
08 if (arrayOfString.length < 3) {
09 System.out.println(" Usage: java com.bif.GreetingServicePublisher
10 [service url] [service port] [service path]");
11 System.out.println("Example: java com.bif.GreetingServicePublisher
12 http://192.168.1.10 9876 BIFWebServices");
13 }
14
15
16 String stringServiceURL = arrayOfString[0];
17
18
19 String stringPort = arrayOfString[1];
20 int intPort = 9876;
21 try {
22 intPort = Integer.parseInt(stringPort);
23 } catch (NumberFormatException numberFormatException) {
24 numberFormatException.printStackTrace();
25 }
26

http://roderickbarnes.com/droid-chronicles-web-services-part-1/ 3/6
13/10/2015 The Droid Chronicles – Web Services: kSOAP2-Based Solutions

27
28 String stringPublicationPath = arrayOfString[2];
29
30 Endpoint.publish(stringServiceURL + ":" + intPort + "/" +
stringPublicationPath, new GreetingServiceImplementation());
}
}

The code block for GreetingServicePublisher, when compiled and run, will make it available on the port of
your choice. It should be invoked with a command line call like

java com.bif.GreetingServicePublisher http://198.168.1.10 9876 BIFWebServices

This will use the built-in web server to make your web service available to clients. The WSDL for your
service can be found, if you used the parameters above, at the following location

http://198.168.1.10:9876/BIFWebServices?wsdl

Paste the location above into a browser URL to see the WSDL.

kSOAP2 – Based Web Service Client

If you are trying to get web services working on your Android device you have a few options. First, there is
kSOAP. What is it? Well, it is a Java-based library for building SOAP clients. It was designed for Java clients
with limited resources (Applets, Android Devices, and embedded solutions). But why do we need kSOAP,
you ask. After all, there are rich libraries and tools in the existing JDKs for creating clients. True that.
But SOAP communications require overhead that may be too much for mobile devices. (That is the thinking.
I do not buy it. My XOOM has a ton of RAM and dual core NVidia chips. And the phones that are coming out
are getting to be pretty well equipped with computing power.) But I do not recommend using kSOAP unless
being mired in APIs is your thing. The whole point of web services was to add a layer of abstraction over the
remote procedure call. In a typical kSOAP project there are numerous (relative) calls to low level APIs. For
example, a simple call to the aforementioned HelloWorld looks like the following:

01 package com.bif.client;
02
03 import java.io.IOException;
04 import org.ksoap2.SoapEnvelope;
05 import org.ksoap2.SoapFault;
06 import org.ksoap2.serialization.SoapObject;
07 import org.ksoap2.serialization.SoapSerializationEnvelope;
08 import org.ksoap2.transport.HttpTransportSE;
09 import org.xmlpull.v1.XmlPullParserException;
10 import android.app.Activity;
11 import android.os.AsyncTask;
12 import android.os.Bundle;
13 import android.view.View;
14 import android.widget.Button;
15 import android.widget.TextView;
16
17 public class KSOAP2Client extends Activity {

http://roderickbarnes.com/droid-chronicles-web-services-part-1/ 4/6
13/10/2015 The Droid Chronicles – Web Services: kSOAP2-Based Solutions

18 private static final String stringMethodName = "getGreeting";


19 private static final String stringNamespace = "http://bif.com/";
20 private static final String stringURL =
21 "http://192.168.1.100:9876/BIFWebServices";
22 TextView textView = null;
23
24 /**
25 * Called when the activity is first created.
26 */
27 public void onCreate(Bundle bundleSavedInstanceState) {
28 super.onCreate(bundleSavedInstanceState);
29 this.setContentView(R.layout.main);
30 this.textView = (TextView)findViewById(R.id.textView);
31
32 this.textView.setText("Testing");
33
34 AsyncTaskGreetingServiceCaller asyncTaskGreetingServiceCaller = new
35 AsyncTaskGreetingServiceCaller();
36 asyncTaskGreetingServiceCaller.execute();
37 }
38
39 private class AsyncTaskGreetingServiceCaller extends AsyncTask<Void, Void,
40 Void> {
41 protected Void doInBackground(Void...voids) {
42 SoapObject soapObject = new SoapObject(KSOAP2Client.stringNamespace,
43 KSOAP2Client.stringMethodName);
44 SoapSerializationEnvelope soapSerializationEnvelope = new
45 SoapSerializationEnvelope(SoapEnvelope.VER11);
46 soapSerializationEnvelope.setOutputSoapObject(soapObject);
47
48 try {
49 HttpTransportSE httpTransportSE = new
50 HttpTransportSE(KSOAP2Client.stringURL);
51 httpTransportSE.debug = true;
52 httpTransportSE.call(KSOAP2Client.stringNamespace +
53 KSOAP2Client.stringMethodName, soapSerializationEnvelope);
54 Object objectResult =
55 (Object)soapSerializationEnvelope.getResponse();
56 textView.setText(objectResult.toString());
57 return null;
} catch (Exception exception) {
exception.printStackTrace();
}

return null;
}
}
}

When this code runs on a tablet you will get a screen similar to the following

http://roderickbarnes.com/droid-chronicles-web-services-part-1/ 5/6
13/10/2015 The Droid Chronicles – Web Services: kSOAP2-Based Solutions

Tablet (Motorola XOOM) Screenshot of UI After Web Service Call

It worked! Okay, I know. It is not really all that cool. Maybe this will help you down the road with your own
Android-based web service client. Let me know if you have any questions. In the next posting I will show
how to get this done using wsclient++. I hope to hear from you soon.

Reading Resources

Kalin, Martin, Java Web Services: Up and Running, (Sebastopol, CA, OReilly Media, 2009)
kSOAP2 – Android, http://code.google.com/p/ksoap2-android

http://roderickbarnes.com/droid-chronicles-web-services-part-1/ 6/6

You might also like