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="192.168.2.100";
 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) {
   e.printStackTrace();
  } finally {
   if (entity!=null)
    try {
     entity.consumeContent();
    } 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) {
     if(keywords==null)
      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())) {
       promo.setName(value);
      } else if("Description".equals(node.getNodeName())) {
       promo.setDescription(value);
      } else if("Venue".equals(node.getNodeName())) {
       promo.setVenue(value);
      } else if("Name".equals(node.getNodeName())) {
       promo.setName(value);
      } else if("DateTime".equals(node.getNodeName())) {
       promo.setDateTime(value);
      }
     }
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   promo=null;
  } 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">
        18sp
        #fff
        fill_parent 
        wrap_content 
        5px
    </style>
    <style name="ContentText">
        14sp
        #000
        #e81
        true
        
        fill_parent 
        wrap_content 
    </style>

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 R.java file to add fields into the id class, so that you can reference the widget from Java code using findViewById(R.id.tvName). Here is the code for the onCreate() method:

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HttpHost target = new HttpHost(SERVER_HOST, SERVER_PORT, "http");
        String keywords = getKeywords(target);
        
        setContentView(R.layout.main);
        if(keywords!=null) {
         PromoInfo promo = searchPromo(target, keywords);
         if(promo!=null) {
          ((TextView)this.findViewById(R.id.tvName)).setText(promo.getName());
          ((TextView)this.findViewById(R.id.tvDescription)).setText(promo.getDescription());
          ((TextView)this.findViewById(R.id.tvDate)).setText(promo.getDateTime());
          ((TextView)this.findViewById(R.id.tvVenue)).setText(promo.getVenue());
         }
        }
    }

Running the application:

Android screenshot

Related Posts:

79 comments:

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 http://127.0.0.1:8081 refused'

Please let me know what is the problem

thanks

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.

thanks!

Unknown 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...

Hi,
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.

Unknown 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

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

gowsalya 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

Mounika 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

Unknown 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

Unknown 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

Unknown 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

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
Education

jefrin said...

Great blog thanks for sharing

blue prism training institute in chennai

vishwa said...

Wow !! Really a nice Article. Thank you so much for your efforts. Definitely, it will be helpful for others. I would like to follow your blog. Share more like this. Thanks Again

priya said...

That was a great message in my carrier, and It's wonderful commands like mind relaxes with understand words of knowledge by information's.
Microsoft Azure online training
Selenium online training
Java online training
Java Script online training
Share Point online training

sasitamil said...

It is better to engaged ourselves in activities we like. I liked the post. Thanks for sharing.
devops online training

aws online training

data science with python online training

data science online training

rpa online training

Chiến SEOCAM said...

Very nice

lưới chống chuột

cửa lưới dạng xếp

cửa lưới tự cuốn

cửa lưới chống muỗi

Chiến SEOCAM said...

Ib qho interesting thiab interesting tsab xov xwm. Tsaug rau sib koom

lều xông hơi mini

mua lều xông hơi ở đâu

lều xông hơi gia đình

bán lều xông hơi

xông hơi hồng ngoại

Chiến SEOCAM said...

Стаття дуже цікава. Дякуємо, що поділилися

GIẢO CỔ LAM GIẢM BÉO

MUA GIẢO CỔ LAM GIẢM BÉO TỐT Ở ĐÂU?

NHỮNG ĐIỀU CHƯA BIẾT VỀ GIẢO CỔ LAM 9 LÁ

Giảo Cổ Lam 5 lá khô hút chân không (500gr)

Chiến SEOCAM said...

这篇文章非常有趣。谢谢你的分享

DIỆT BỌ CHÉT MÈO BẰNG NHỮNG CÁCH TỰ NHIÊN

DỊCH VỤ DIỆT GIÁN ĐỨC NHANH VÀ HIỆU QUẢ NHẤT HIỆN NAY

DIỆT CHUỘT TẬN GỐC

DIỆT MỐI TẬN GỐC

Chris Hemsworth said...

The article is so informative. This is more helpful. Thanks for sharing.

Learn best software testing online certification course class in chennai with placement
Best selenium testing online course training in chennai
Best online software testing training course institute in chennai with placement

Anonymous said...

nice blog
get best placement at VSIPL

digital marketing services
Web development Services
seo network point

Anonymous said...

nice blog
get best placement at VSIPL

digital marketing services
Web development Services
seo network point

divi said...

awesome article,the content has very informative ideas, waiting for the next update...
thanks for your information really good and very nice web design company in velachery

Noithatbaoankids said...

Bàn học trẻ em

Phòng ngủ trẻ em

Giường tầng

svrtechnologies said...

thanks for sharing such an useful stuff....

apex course

vijay said...

I liked your blog.Thanks for your interest in sharing the information.keep updating.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

vijay said...

Awesome..I read this post so nice and very imformative information...thanks for sharing
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

raju said...

nice.....!
inplant training in chennai
inplant training in chennai for it.php
panama web hosting
syria hosting
services hosting
afghanistan shared web hosting
andorra web hosting
belarus web hosting
brunei darussalam hosting
inplant training in chennai

shri said...

nice...
internship in chennai for ece students
internships in chennai for cse students 2019
Inplant training in chennai
internship for eee students
free internship in chennai
eee internship in chennai
internship for ece students in chennai
inplant training in bangalore for cse
inplant training in bangalore
ccna training in chennai


Durai Moorthy said...

This is very good quality article and interesting..& This post has a nice one. share more updates.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

Shopclues Winner List said...

Shopclues winner list 2020 here came up with a list of offers where you can win special shopclues prize by just playing a game & win prizes.
Shopclues lucky draw 2020
Shopclues winner name 2020
Shopclues prize list 2020

GlobalEmployees said...

Read my post here
Java programmer
Java programmer
Java programmer

Rajesh Anbu said...

Your article is very informative. Thanks for sharing the valuable information.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

online training course said...

I just loved your article on the beginners guide to starting a blog. Thank you for this article. microsoft sharepoint training with highly experienced facutly.

Kerrthika K said...

Thank you much more for sharing the wonderful post. Keep updating here...
Advanced Excel Course in Chennai
Advanced Excel Training
Linux Training in Chennai
Graphic Design Courses in Chennai
Pega Training in Chennai
Tableau Training in Chennai
Oracle DBA Training in Chennai
Oracle Training in Chennai
Unix Training in Chennai
JMeter Training in Chennai
Advanced Excel Training in Chennai

Máy mátxa chân said...

Good

Bồn ngâm chân

máy ngâm chân

bồn massage chân

may mat xa chan

svrtechnologies said...

This is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.
microsoft azure training

Ganesh said...

Excellent Blog..Thanks for sharing..Nice one..

java training in chennai BITA Academy | best java training institute in chennai | java course near me | java training in tambaram | java training in velachery chennai | dot net training in chennai BITA Academy | best dot net training institute in chennai | dot net training center in chennai | dot net certification training in chennai | java certification training in chennai | advanced dot net training in chennai | advanced java training in chennai

akshaya said...

I am glad to read the content of this blog, which seems accurate. The information that you have given in this blog would be more helpful for the readers.
Web Designing Course Training in Chennai | Web Designing Course Training in annanagar | Web Designing Course Training in omr | Web Designing Course Training in porur | Web Designing Course Training in tambaram | Web Designing Course Training in velachery


James Williams said...

Nice Article. I hope really enjoyed while reading the article, Thanks for sharing your ideas.
Java Online Training
Python Online Training
PHP Online Training

radhika said...

Nice post. This provides good insight. It has all the valid points and is very impressive. Great!
AWS training in Chennai

AWS Online Training in Chennai

AWS training in Bangalore

AWS training in Hyderabad

AWS training in Coimbatore

AWS training

pooja said...

nice artical.thanks for sharing with as.




zplus cyber secure technology pvt. Ltd.

Michael said...

http://alltopc.com/2020/09/06/movavi-slideshow-maker-6-for-mac-free-download-movavi-slideshow-maker-6-for-mac-free/

Rose said...

https://getdailybook.com/spillover-by-david-quammen-pdf-download/

Web Hosting in India said...

Thank you for Amazing Article. Really This Will Help me For while I am Selecting Hosting.
Web Hosting Service In Surat

Unknown said...

Good blog thanks for sharing
Angular course
Angular training

Sharma said...

Very nice post here and thanks for it. I always like and such super content of this post. Excellent and very cool idea and great content of different kinds of valuable information.

Digital Marketing Training in Chennai
Digital Marketing Training in Bangalore
Digital Marketing Training in Delhi
Digital Marketing Online Training

Josh said...

edumeet | python training in chennai
hadoop training in chennai
zoom alternative

jhansi said...

Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
tally training in chennai

hadoop training in chennai

sap training in chennai

oracle training in chennai

angular js training in chennai

saketh321 said...


I see the greatest contents on your blog and I extremely love reading them. ExcelR Data Science Course In Pune

burkkevin said...

This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post. killer frost jacket

Sầu nhân thế said...

hay

máy xông tinh dầu bằng điện

máy khuếch tán tinh dầu silent night

máy xông tinh dầu đuổi muỗi

máy khuếch tán tinh dầu hà nội

salome said...

interesting to read and useful.
Angular training in Chennai

INFYCLE TECHNOLOGIES said...

Infycle Technologies, the top software training institute and placement center in Chennai offers the No.1 Digital Marketing course in Chennai for freshers, students, and tech professionals at the best offers. In addition to Digital Marketing, other in-demand courses such as DevOps, Data Science, Python, Selenium, Big Data, Java, Power BI, Oracle will also be trained with 200% practical classes. After the completion of training, the trainees will be sent for placement interviews in the top MNC's. Call 7504633633 to get more info and a free demo.

eddielydon said...

Thanks for the best blog. it was very useful for me.keep sharing such ideas in the future as well. bandit leather jacket

Bulk Tote Bags said...

Những chia sẻ quá hay và tuyệt vời


The best reputable and quality food container bag

What is the application of 4 loops of bulk Tote Bags?

Preeminent advantages of waterproof jumbo bags

3 things to know about 500kg 1000kg baffled bulk bag

George Mark said...

Statistics students and professor are worried to find the deviation calculator because their work depends on it. 12th Doctor Coat

Jobi Johnson said...

I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. thanos vest

karlchrist impoludo said...


organic chemistry notes
gamsat organic chemistry
cbse organic chemistry
iit organic chemistry

unknown said...

Thanks for sharing this premium article free of cost i really like your article . you can alsoshop here

closetofdeal said...

travisscottshop I really appreciate the kind of topics you post here.

unknown said...

The data you have posted is extremely helpful. chromeheartsoutfit.com The locales you have alluded was great. Much obliged for sharing.

Kary Christ said...


SS03 Single Fiber Stripper
fujikura fiber cutter

srikanth digital said...

I am thoroughly impressed by your excellent post and review. Please continue to produce such remarkable content. Thank you!

Best Junior Colleges in Hyderabad for MEC

srikanth digital said...

I'm delighted to express that your post is quite captivating. I've gained fresh insights from your write-up, and you're doing an exceptional job. Keep up the good work. For More Visit the below website

Best CMA institute in Hyderabad

srikanth digital said...

I am delighted to express that your post is captivating to read. I acquire fresh knowledge from your article, and you are doing an excellent job. Please continue your great work.

CMA institute Hyderabad

srikanth digital said...

I haven't come across such a valuable resource in a long time. It is well-written and contains excellent information. I am truly grateful to you for sharing it.

CMA Coaching Centres in Hyderabad

srikanth digital said...

I haven't come across such a valuable resource in a long time. It is excellently written and contains incredibly useful information. I truly cannot express my gratitude enough for sharing it.

CMA Colleges in Hyderabad

srikanth digital said...

Your blog is truly amazing. The content is informative and full of knowledge. I had a great time reading your article. Please continue to share more content like this. Thank you.

Best CMA Coaching in Hyderabad

johnkennedy said...

thankful for the content "Odoo Training
odoo erp training
odoo online training
" "Odoo Support & Maintenance
Odoo Maintenance Module
"

Anna smith said...

Choosing the best Data Science course depends on your current skill level, learning style, and career goals. check out Best Data Science course in kochicourse in kochi

David said...

I am sure you have managed all the data to complete your research that's y you have written such a great post, now I have to search for brown cafe racer jacket slim fit and I am sure will complete this task within some moments!

instruments care said...

UV Spectrophotometer repairs & service
Refurbished instruments (GC, HPLC, UV, AAS, Viscometer)