Tuesday, July 29, 2008

Coding REST Web Services on Google Android

When looking at utilitizing a SOA architecture to support SportsFlash, I had to investigate Android's ability to work with web services. From Google Android forums, I was first pointed to KSoap2 (http://ksoap2.sourceforge.net/), with implementations described here:

However, I was a little concerned by some of the difficulties described here, and I wanted to look at REST based services, which I thought would create the simple, lightweight API to our database that we require. I credit the publication "Unlocking Android", by W.Frank Albleson, Charlie Collins, Robi Sen, and Robert Cooper and Professor Ron Czik of Boston University. Using the SAX XML Parser

(http://code.google.com/android/reference/org/xml/sax/XMLReader.html)
you can create a REST Web Service that returns xml (or JSON), which is parsed by SAX.

A template for usuage could look like this:


try {
URL url = new URL(this.query + position);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
ObjectHandler handler = new ObjectHandler();
xr.setContentHandler(handler);
xr.parse(new InputSource(url.openStream()));
// after parsed, get record
r = handler.getRecord();
} catch (Exception e) {
Log.e(Constants.LOGTAG, " " + CLASSTAG, e);
}

where your ObjectHandler is a class that extends DefaultHandler (http://code.google.com/android/reference/org/xml/sax/helpers/DefaultHandler.html) where you override methods like startDocument(), startElement(), characters() ... etc to handle the reading and parsing of your xml stream from your REST Web Service.

1 comment:

yoshinav said...

If you experience a FileNotFoundException when trying to open a stream to your URL (web resource), refer to following thread:

http://groups.google.com/group/android-sportsflash/browse_thread/thread/6b9b4b062220704e