Friday, 22 August 2008

Consuming Web Services from Android

Earlier this week, Google released Android 0.9 SDK Beta. As usual, I couldn't wait to try it out.

Unlike JavaME (especially MIDP 1.0), Android is targetting mobile devices with more grunt - it's bundled with many open source libraries, such as Apache Harmony (open source Java SE), Unicode library, JUnit, Apache Commons, ASN.1 libarary and more from Bouncy Castle, kXML, etc. The android.jar file is 11MB!

It is time to write a web service consumer on Android, to consume my WCF web service as well as RESTful service that I developed for a demo.

The Android does not contain any tools to help building SOAP based web service clients. Google is a proponent of REST services. It is no surprise that the SDK is not bundled with any SOAP-related tools. An alternative is to add kSOAP 2 to my test project. But I quickly dismissed the idea as my web service built in WCF is not JSR-172 compliant.

Like my exercise in JavaME, I decided to call the RESTful version of the same service built in NetBeans 6.1 instead.

I created a new Android project - SvdemoAndroid, using Eclipse 3.4 with the Android plugin installed. Because my Android Activity will be accessing the internet for the HTTP connection (although it's hosted on my machine), I had to add the line <uses-permission android:name="android.permission.INTERNET" /> to my AndroidManifest.xml file. Now the file looks something like:

    <uses-permission android:name="android.permission.INTERNET" /> 
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Android is bundled with Apache HttpClient 4. So invoking a REST service is simply a matter of openning up a HTTP link using the HttpClient and process the response. The following two methods show the consumption of two different RESTful services. The first method getKeywords() calls a service returning a plain text on HTTP.

        static String SERVER_HOST="";
 static int SERVER_PORT = 8080;
 static String URL1 = "/SvdemoRestful/resources/mySpace?url=http://wpickup02/MySpace_Com_John.htm";
 static String URL2 = "/SvdemoRestful/resources/promo";
     * Call the RESTful service to get a list of keywords from the web page.
     * @param target - the target HTTP host for the RESTful service.
     * @return - comma delimited keywords. May contain spaces. If no keywords found, return null.
    private String getKeywords(HttpHost target) {
        String keywords=null;
     HttpEntity entity = null;
     HttpClient client = new DefaultHttpClient();
     HttpGet get = new HttpGet(URL1);
     try {
   HttpResponse response=client.execute(target, get);
   entity = response.getEntity();
   keywords = EntityUtils.toString(entity);
  } catch (Exception e) {
  } finally {
   if (entity!=null)
    try {
    } catch (IOException e) {}
  return keywords;

The second method calls another service (on URL2). This service returns a XML string containing the details of a Promotion. Unlike JavaME, Android SDK is bundled with DOM parser. Since my XML string is pretty short I decided to use DOM instead of kXML's pull parser. Note that PromoInfo is just a data object holding all the promotion information in its fields.

     * Call the REST service to retrieve the first matching promotion based
     * on the give keywords. If none found, return null.
     * @param target - the target HTTP host for the REST service.
     * @param keywords - comma delimited keywords. May contain spaces.
     * @return - PromoInfo that matches the keywords. If error or no match, return null.
    private PromoInfo searchPromo(HttpHost target, String keywords) {
      return null;
     PromoInfo promo=null;
     Document doc = null;
     HttpClient client = new DefaultHttpClient();
     HttpGet get = new HttpGet(URL2+"/"+keywords.replaceAll(" ", "%20"));
     try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = factory.newDocumentBuilder();
   HttpEntity entity = client.execute(target, get).getEntity();
   doc = builder.parse(entity.getContent());
   NodeList promotions = doc.getElementsByTagName("Promotion");
   if(promotions!=null) {
    Node promoNode = promotions.item(0);
    if (promoNode!=null) {
     promo=new PromoInfo();
     NodeList nodeList = promoNode.getChildNodes();
     int len = nodeList.getLength();
     for(int i=0; i<len; i++) {
      Node node = nodeList.item(i);
      String value = this.getNodeValue(node);
      if("Name".equals(node.getNodeName())) {
      } else if("Description".equals(node.getNodeName())) {
      } else if("Venue".equals(node.getNodeName())) {
      } else if("Name".equals(node.getNodeName())) {
      } else if("DateTime".equals(node.getNodeName())) {
  } catch (Exception e) {
  } finally {
  return promo;
    private String getNodeValue(Node node) {
     NodeList children = node.getChildNodes();
     if(children.getLength()>0) {
      return children.item(0).getNodeValue();
     } else
      return null;

Now that I have invoked the web services and got the data back to my Android phone, it is time to display them on screen. Android adopts a similar approach to Microsoft WPF, where you can define the view layout and styles in a XML file, so that the Java code is freed up from screen rendering code and can focus more on the business logic.

I created a style.xml file under the {project}/res/values directory to define the styles for my screen widgets.

    <style name="LabelText">
    <style name="ContentText">

Then my view layout XML can use the styles. Here is the {project}/res/layout/main.xml file:

    <TextView style="@style/LabelText" android:text="Name:"/>
    <TextView style="@style/ContentText" android:id="@+id/tvName" />
    <TextView style="@style/LabelText" android:text="Description:"/>
    <TextView style="@style/ContentText" android:id="@+id/tvDescription" />
    <TextView style="@style/LabelText" android:text="Venue:"/>
    <TextView style="@style/ContentText" android:id="@+id/tvVenue" />
    <TextView style="@style/LabelText" android:text="Date:"/>
    <TextView style="@style/ContentText" android:id="@+id/tvDate" />

Note that by adding the android:text="@+id/tvName", the Android Eclipse Plugin will automatically regenerate the file to add fields into the id class, so that you can reference the widget from Java code using findViewById( Here is the code for the onCreate() method:

/** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        HttpHost target = new HttpHost(SERVER_HOST, SERVER_PORT, "http");
        String keywords = getKeywords(target);
        if(keywords!=null) {
         PromoInfo promo = searchPromo(target, keywords);
         if(promo!=null) {

Running the application:

Android screenshot

Related Posts:


RTN said...

Thanks Mate for your post, when i try to conncet i am getting this error message in my android LogCat 'org.apache.http.conn.HttpHostConnectException: Connection to refused'

Please let me know what is the problem


Anonymous said...

THanks for the post!

does you know how to configure an autentification?. for example i want to consume a REST service in a host that ask me for user and password.


ArKanJiL said...

Great post! Very helpful, and gives a lot of great ideas. Thanks!

rssl said...

RTN: you have to use your physical IP address in the URL. Otherwise android thinks that localhost is him.

El Abuelo said...

Hi, I am nicolas. Iam trying to connect to a external DB. This would be the way to do it?.
Thank you

Android app developer said...

Come to your blog is my pleasure, your commodity abounding of affluent colors of life; and acceptation with life, affluent in abstract knowledge. Look advanced to your updates.

Jeevan said...

I tried this example but I am getting errors,as PromoInfo cannot be resolved to a typ,

Maxwell Mcpherson said...

There are a couple of particulars when it comes to WCF and being interoperable with java you want to be careful about.

niaziakmal khan said...

Programming is combination of intelligent and creative work. Programmers can do anything with code. The entire Programming tutorials that you mention here on this blog are awesome. Beginners Heap also provides latest tutorials of Programming from beginning to advance level.
Be with us to learn programming in new and creative way.

Geetha Devi said...

It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.|Best Android Training in Velachery | android development course fees in chennai

Saranya N said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.Android Training in chennai with placement | Android Training in velachery

vigneswaran said...

It's really interesting I'll be read that many of the bloggers relevant android development that's time I read that's your tips helped me and clarify the new thing. pretty explicit helpful content.

Java Training in Chennai | Android Training in Chennai | Hadoop Training in Velachery | Selenium Training in Chennai with placement

johnsy sai said...

Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
digital marketing training in tambaram

digital marketing training in annanagar

digital marketing training in marathahalli

digital marketing training in rajajinagar

Digital Marketing online training

Mouni yoga said...

Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
python training in tambaram
python training in annanagar
python training in velachery

ummi ari said...

Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
Blueprism online training

Blue Prism Training in Pune

Blueprism training in tambaram

ummi ari said...

Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
Blueprism online training

Blue Prism Training in Pune

Blueprism training in tambaram

geetha sridhar said...

It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
Data Science training in kalyan nagar
Data Science training in OMR
selenium training in chennai
Data Science with Python training in chenni
Data Science training in chennai
Data science training in velachery

afiah ahamed said...

Fantastic work! This is the type of information that should follow collective approximately the web. Embarrassment captivating position Google for not positioning this transmit higher! Enlarge taking place greater than and visit my web situate

java training in omr | oracle training in chennai

java training in annanagar | java training in chennai

Anonymous said...

Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
angularjs-Training in velachery

angularjs Training in bangalore

angularjs Training in bangalore

angularjs Training in btm

angularjs Training in electronic-city

Sai Elakiyaa said...

I have never read more interesting articles than yours before. You make me so easy to understand and I will continue to share this site. Thank you very much and more power!

Selenium Training in Chennai
software testing selenium training
ios developer course in chennai
French Classes in Chennai
android development course in chennai
android course in chennai with placement

Vicky Ram said...

Really amazing information!!! Thanks for your blog.

Guest posting sites