29
 Develop an Apache HttpClient client for Android to a JAX-RS web service Learn to create an Apache HttpClient Android client Skill Level: Intermediate Deepak Vohra Consultant Independent 11 Oct 2011 Create JAX-RS web service access with the Apache HttpClient library. Jersey, a reference implementation for JAX-RS, simplifies development of RESTful web services in the Java™ environment. Android is a popular smartphone and this article shows you how to create a JAX-RS client for Android. You'll create an Apache HttpClient library client to a JAX-RS web service. Introduction Explore Spring Android Spring Android is another option. Learn to access a RESTful web servic e with the Spring Android REST client in this articl e, also by Deepak: Develop a Spring client for Android to a JAX-RS web service The REST software architecture is based on transferring representation of resources. RESTful web services offer some advantages: They are simple, light weight, and fast. A RESTf ul web servi ce exposes a set of resources identif ied by URIs. Resources respond to the HTTP methods GET, POST, PUT, and DELETE. Resources may be accessed in various formats, such as HTML, plain text, XML, PDF, JPEG, or JSON. The Java API for RESTful web services (JAX-RS) is defined in JSR 311. Jersey is a reference implementation for JAX-RS that simplifies Develop an Apache HttpClient client for Android to a JAX-RS web service  Trademarks  © Copyright IBM Corporation 2011  Page 1 of 29

IBM Developer Works Android Jax Rs

Embed Size (px)

Citation preview

Page 1: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 1/29

 

Develop an Apache HttpClient client for Android toa JAX-RS web service

Learn to create an Apache HttpClient Android client

Skill Level: Intermediate

Deepak VohraConsultant

Independent

11 Oct 2011

Create JAX-RS web service access with the Apache HttpClient library. Jersey, areference implementation for JAX-RS, simplifies development of RESTful webservices in the Java™ environment. Android is a popular smartphone and this articleshows you how to create a JAX-RS client for Android. You'll create an Apache

HttpClient library client to a JAX-RS web service.

Introduction

Explore Spring AndroidSpring Android is another option. Learn to access a RESTful webservice with the Spring Android REST client in this article, also byDeepak:

Develop a Spring client for Android to a JAX-RS web service

The REST software architecture is based on transferring representation ofresources. RESTful web services offer some advantages: They are simple,lightweight, and fast. A RESTful web service exposes a set of resources identified byURIs. Resources respond to the HTTP methods GET, POST, PUT, and DELETE.Resources may be accessed in various formats, such as HTML, plain text, XML,PDF, JPEG, or JSON. The Java API for RESTful web services (JAX-RS) is definedin JSR 311. Jersey is a reference implementation for JAX-RS that simplifies

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 1 of 29

Page 2: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 2/29

 

development of RESTful web services in Java.

In this article, use the Apache HttpClient library to create a JAX-RS client forAndroid—the popular smartphone platform. You can download the sample codeused in this article.

Setting up the environment

Frequently used abbreviations

• API: Application programming interface

• HTML: HyperText Markup Language

• HTTP: HyperText Transfer Protocol

• IDE: Integrated Development Environment

• JSON: JavaScript Object Notation

• MIME: Multipurpose Internet Mail Extensions

• POJO: Plain Old Java Object

• REST: Representational State Transfer

• SDK: Software Development Kit

• UI: User Interface

• URI: Uniform Resource Identifier

• URL: Uniform Resource Locator

• XML: Extensible Markup Language

Before you can create a client for a JAX-RS web service, you need to set up theenvironment. See Resources for links.

1. Install Eclipse.

2. Install the Android Development Tools (ADT) plug-in for Eclipse, whichprovides a set of extensions to develop Android applications in Eclipse.

3. Install the SDK Platform for Android 2.2.The Android SDK provides toolsfor developing Android applications.

4. Create an Android Virtual Device (AVD), which is an emulator for Android,in Eclipse.

5. Download the Jersey archive, jersey-archive-1.4.zip, containing theJersey JARs and core dependencies. Download the Jersey bundle JAR

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 2 of 29

Page 3: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 3/29

 

 jersey-bundle-1.4.jar.Jersey is built using JDK 6.0, so you also need to install JDK 6.0.

6. Install a web server such as Tomcat, or an application server such asWebSphere®, or WebLogic server. Add the Jersey JAR files in Listing 1to the runtime CLASSPATH of the application/web server.Listing 1. Jersey JAR Files

C:\Jersey\jersey-bundle-1.4.jar;C:\Jersey\jersey-archive-1.4\lib\asm-3.1.jar;C:\Jersey\jersey-archive-1.4\lib\jsr311-api-1.1.1.jar

Creating an Eclipse project

In this section, you will create a web project and add the JAX-RS facet to the project.Use the following steps to create an Eclipse project.

1. Select File > New, and in the New window, select Web > Dynamic WebProject. Click Next.

2. Specify a Project name (for example, AndroidJAX-RS) and click NewRuntime, to configure a new target runtime for your WebSphere, Tomcat,or WebLogic server. Figure 1 shows the completed Dynamic Web Projectwindow.

Figure 1. Configure a new runtime

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 3 of 29

Page 4: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 4/29

 

3. In the New Server Runtime Environment window, select a server, such asthe Tomcat server, the WebSphere server, or the WebLogic server. ClickNext, as in Figure 2.Figure 2. Select an application or web server

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 4 of 29

Page 5: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 5/29

 

4. In the New IBM WebSphere v6.0 Runtime window, configure a JRE andthe IBM WebSphere Installation Directory. Click Next in the Dynamic WebProject dialog. Select the default Java settings for Source folder andOutput folder, and click Next.

5. Specify Context root as AndroidJAX-RS, select the default ContentDirectory, and click Finish.

A Dynamic Web Project is created and gets added to Project Explorer.Right-click on the project node and select Properties.

6. Select Project Facets, then select the JAX-RS (REST Web Services)1.1 project facet. Click Further configuration required, as in Figure 3.Figure 3. Configure the JAX-RS Project Facet

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 5 of 29

Page 6: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 6/29

 

7. In the JAX-RS Capabilities window, specify a Servlet name (JAX-RSServlet) and configure a JAX-RS Implementation library. Select Type asUser Library and click Manage.

8. In the User Libraries window, click New. In the New User Library dialog,specify a User library name and click OK.A user library is added. Click Add JARs to add Jersey JARs to the userlibrary. As in Figure 4, add the following Jersey JARs:

• jersey-bundle-1.4.jar

• C:\Jersey\jersey-archive-1.4\lib\asm-3.1.jar

• C:\Jersey\jersey-archive-1.4\lib\jsr311-api-1.1.1.jarClick OK.Figure 4. Add Jersey JAR files

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 6 of 29

Page 7: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 7/29

 

9. In the JAX-RS Capabilities window, specify the JAX-RS servlet classname ascom.sun.jersey.spi.container.servlet.ServletContainer,

as in Figure 5. Click OK.Figure 5. Specify the JAX-RS servlet class

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 7 of 29

Page 8: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 8/29

 

10. In the Project Facets window, click Apply as in Figure 6, then click OK.Figure 6. Apply the JAX-RS Project Facet

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 8 of 29

Page 9: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 9/29

 

The targeted runtimes are configured with the JAX-RS project facet. Click OK in theProperties dialog.

The JAX-RS User libraries get added to the project, and the JAX-RS servlet andservlet mapping get configured in web.xml. You need to add init-param elementsfor the com.sun.jersey.config.property.resourceConfigClass and thecom.sun.jersey.config.property.packages init parameters. Listing 2shows the web.xml.

Listing 2. web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.comxml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<servlet><description>JAX-RS Tools Generated - Do not modify</description><servlet-name>JAX-RS Servlet</servlet-name><servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class><init-param>

<param-name>com.sun.jersey.config.property.resourceConfigClass</param-name>

<param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value></init-param><init-param>

<param-name>com.sun.jersey.config.property.packages</param-name><param-value>jaxrs</param-value>

</init-param><load-on-startup>1</load-on-startup>

</servlet><servlet-mapping>

<servlet-name>JAX-RS Servlet</servlet-name><url-pattern>/jaxrs/*</url-pattern>

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 9 of 29

Page 10: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 10/29

 

</servlet-mapping></web-app>

Creating and running a resource class

The next step is to create a RESTful web service resource using a root resourceclass. A root resource class is a POJO annotated with the @PATH annotation. Itconsists of at least one method annotated with the @PATH annotation or @GET,@PUT, @POST or @DELETE.

1. Select File > New > Other. In the New dialog, select Java > Class, andclick Finish.

2. In the New Java Class window, as in Figure 7, specify:

• A Source folder: AndroidJAX-RS/src

• Package: jaxrs

• Class name: HelloWorldResource

Click Finish.

Figure 7. Create the resource class

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 10 of 29

Page 11: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 11/29

 

Annotate the Java class with the @PATH annotation. The code in Listing 3 specifiesthe URI path on which the Java class shall be hosted as /helloworld.

Listing 3. Annotate resource class with @Path

@Path("/helloworld")public class HelloWorldResource {...}

To add resource methods to produce three different MIME types, add the

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 11 of 29

Page 12: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 12/29

 

getClichedMessage(), getXMLMessage(), and getHTMLMessage() methods.Annotate each method with the @GET annotation, which indicates that the methodsshall process HTTP GET requests. Specify String as the return type for each ofthe methods. Annotate each method with the @PRODUCES annotation, and specify adifferent MIME type for each method.

Now you want to output a "Hello JAX-RS" method using the MIME typestext/plain, text/xml, and text/html. The getXMLMessage method isannotated with the @Produces ("text/xml") annotation that produces an XMLmessage. Uncomment only one of the methods annotated with the @GET method. Ifno other distinguishing path component is specified, the @GET request is routed tothe method annotated with @GET. If multiple methods match a request URI, theJAX-RS selection algorithm is used to select the resource method. For example, youcan specify multiple methods with the @GET annotation by using a different path idfor the methods annotated with @GET. Listing 4 shows the root resource class.

Listing 4. HelloWorldResource.java

package jaxrs;

import javax.ws.rs.GET;import javax.ws.rs.Produces;import javax.ws.rs.Path;import javax.ws.rs.core.MediaType;

// The Java class will be hosted at the URI path //"/helloworld"@Path("/helloworld")public class HelloWorldResource {

// The Java method will process HTTP GET requests@GET

// The Java method will produce content identified by the MIME Media// type "text/plain"@Produces("text/plain")public String getClichedMessage() {

// Return some cliched textual contentreturn "Hello Android";}

// @GET// @Produces("text/xml")// public String getXMLMessage() {// return "<?xml version=\"1.0\"?>" + "<hello> Hello Android" + "</hello>";// }

// @GET//@Produces("text/html")//public String getHTMLMessage() {

//return "<html> " + "<title>" + "Hello Android" + "</title>"// + "<body><h1>" + "Hello Android" + "</body></h1>" +

"</html> ";// }

}

Run the resource class to produce different types of output. Comment out themethods that are not to be tested, and keep one method uncommented for each of

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 12 of 29

Page 13: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 13/29

 

the test runs. First, test the text/xml MIME type as output. Start theapplication/web server if not already started. Right-click on the resource class andselect Run As > Run on Server, as in Figure 8.

Figure 8. Run the resource class

On the server, the init parametercom.sun.jersey.config.property.resourceConfigClass is initiated ascom.sun.jersey.api.core.PackagesResourceConfig and the initparameter com.sun.jersey.config.property.packages is initiated asjaxrs, as specified in web.xml. The root resource classjaxrs.HelloWorldResource is found. The Jersey application v1.4 is initiated,and the AndroidJAX-RS module deploys on the server.

Creating an Android client project

In this section you'll create an Android project in which you create the JAX-RS clientfor Android.

1. In the Eclipse IDE, select File > New. In the New dialog, select Android >Android Project, then click Next.

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 13 of 29

Page 14: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 14/29

 

2. Complete the fields in the New Android Project window, as in Figure 9.

• Project name: AndroidJAXRSClient

• Build Target: Android Platform 2.2 API 8

• Properties: Application name AndroidJAXRSClient and Packagename android.jaxrs

• Select Create Activity, and specify Activity classAndroidJAXRSClient.An activity represents a user interaction, and the class extending theActivity class creates a window for a UI.

• Minimum SDK Version: 8

• Click Next

Figure 9. Create the JAX-RS client class

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 14 of 29

Page 15: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 15/29

 

The files in the Android project are:

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 15 of 29

Page 16: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 16/29

 

• An activity class (AndroidJAXRSClient), which extends the Activity

class

• The res/layout/main.xml file to specify the layout of the Androidapplication

• The AndroidManifest.xml file, which contains application configurationinformation such as the package name, application components,processes, permissions, and minimum API level for the Android system

In the res/layout/main.xml file, specify the layout of the Android UI components.Create a LinearLayout with android:orientation="vertical". You'llcreate a UI in which the response from the web service is displayed as a textmessage. Add a TextView element with id jaxrs to display the JAX-WS webservice response for a method call to one of the get methods. The methodinvocation gets a Hello message as a response in either XML, HTML, or text. Listing5 shows the main.xml file:

Listing 5. 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:id="@+id/jaxrs"android:layout_width="fill_parent" android:layout_height="wrap_content"

/></LinearLayout>

To access the JAX-RS web service from an Android device, enable theandroid.permission.INTERNET permission, in AndroidManifest.xml, whichallows applications to open network sockets. Add the uses-permission elementin Listing 6.

Listing 6. Set INTERNET permission

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Specify the minimum Android version with the uses-sdk element. TheAndroidJAXRSClient activity, the intent-filter, and action are specified

with the activity element and sub-elements. Listing 7 shows theAndroidManifest.xml file.

Listing 7. AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="android.jaxrs" android:versionCode="1" android:versionName="1.0">

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 16 of 29

Page 17: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 17/29

 

<uses-sdk android:minSdkVersion="8" /><application android:icon="@drawable/icon" android:label="@string/app_name">

<activity android:name=".AndroidJAXRSClient" 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-sdk android:minSdkVersion="8" /><uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>

The Android SDK includes the Apache HttpClient library. Import the classes inListing 8 into AndroidJAXRSClient.

Listing 8. Apache HttpClient library

org.apache.http.HttpEntity;org.apache.http.HttpResponse;

org.apache.http.client.ClientProtocolException;org.apache.http.client.HttpClient;org.apache.http.client.methods.HttpGet;org.apache.http.impl.client.DefaultHttpClient;

The AndroidJAXRSClient class extends the Activity class. TheonCreate(Bundle savedInstanceState) method is invoked when the activityis first called. Define the user interface using the setContentView method and thelayout resource, as in Listing 9.

Listing 9. Define the UI

setContentView(R.layout.main);

Listing 10 shows how to create an Android widget TextView object, using thefindViewById method on the TextView element, with the id jaxrs that wasdefined in main.xml.

Listing 10. Create an Android widget

TextView jaxrs = (TextView) findViewById(R.id.jaxrs);

The default implementation of HttpClient is DefaultHttpClient. Create aDefaultHttpClient object, as Listing 11.

Listing 11. Create an HttpClient

HttpClient httpclient = new DefaultHttpClient();

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 17 of 29

Page 18: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 18/29

 

Create an HttpGet object to retrieve information from the server, as in Listing 12.Specify the URL to the resource hosted on the URI path /helloworld. Specify theIP address for host instead of localhost. The client runs on the Android device, andlocalhost for the Android device is not the host on which the JAX-RS web serviceruns (unless the JAX-RS web service is also hosted on the Android device, which is

not the case in this example).

Listing 12. Create an HttpGet object

HttpGet request = new HttpGet("http://192.168.1.68:7001/AndroidJAX-RS/jaxrs/helloworld");

Specify acceptable media types using the Accept header. Set only one of themedia types, which corresponds to the media type produced in the JAX-RS webservice, in the Accept header. In the first run, set the Accept header to text/xml

to output the text/xml response, as in Listing 13.

Listing 13. Set the Accept Header

request.addHeader("Accept", "text/xml");//request.addHeader("Accept", "text/html");//request.addHeader("Accept", "text/plain");

Test the output of each of the response types (plain text, html, and XML). Theaccepted response type should match the MIME type produced in the resourceclass. The MIME type produced by the resource class should match an acceptableMIME type. If the produced MIME type and the acceptable MIME type do not match,a com.sun.jersey.api.client.UniformInterfaceException is generated.

For example, set the acceptable MIME type to text/xml and the produced MIMEtype to application/xml. The UniformInterfaceException is generated. Asin Listing 14, invoke the execute() method of the HttpClient, with the HttpGet

method as an argument, to retrieve the HttpResponse object.

Listing 14. Get the HttpResponse

HttpResponse response = httpclient.execute(request);

From the HttpResponse obtain the HttpEntity using the getEntity method

(Listing 15).

Listing 15. Get the HttpEntity

HttpEntity entity = response.getEntity();

Get the content as an InputStream from the HttpGet using the getContent()

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 18 of 29

Page 19: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 19/29

 

method (Listing 16).

Listing 16. Create an InputStream from the HttpEntity

InputStream instream = entity.getContent();

Create a StringBuilder for the message returned from the JAX-RS web service(Listing 17).

Listing 17. Create a StringBuilder

StringBuilder sb = new StringBuilder();

Create a BufferedReader from the InputStream (Listing 18).

Listing 18. Create a BufferedReader

BufferedReader r = new BufferedReader(new InputStreamReader(instream));

Read each line from the BufferedReader and add it to the StringBuilder

(Listing 19).

Listing 19. Read the BufferedReader

for (String line = r.readLine(); line != null; line = r.readLine()) {

sb.append(line);}

Get the String message from the StringBuilder and close the InputStream

(Listing 20).

Listing 20. Get the StringBuilder message

String jaxrsmessage = sb.toString();instream.close();

Set the String message on the TextView UI component (Listing 21).

Listing 21. Set the StringBuilder message

jaxrs.setText(jaxrsmessage);

Listing 22 shows the AndroidJAXRSClient class.

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 19 of 29

Page 20: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 20/29

 

Listing 22. AndroidJAXRSClient.java

package android.jaxrs;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;import java.io.BufferedReader;

import java.io.InputStream;import java.io.InputStreamReader;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;

public class AndroidJAXRSClient extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);setContentView(R.layout.main);

TextView jaxrs = (TextView) findViewById(R.id.jaxrs);try {

HttpClient httpclient = new DefaultHttpClient();HttpGet request = new HttpGet(

"http://192.168.1.68:7001/AndroidJAX-RS/jaxrs/helloworld");

//request.addHeader("Accept", "text/html");// request.addHeader("Accept", "text/xml");

request.addHeader("Accept", "text/plain");HttpResponse response = httpclient.execute(request);HttpEntity entity = response.getEntity();InputStream instream = entity.getContent();String jaxrsmessage = read(instream);jaxrs.setText(jaxrsmessage);

} catch (ClientProtocolException e) {e.printStackTrace();

} catch (IOException e) {e.printStackTrace();}

}

private static String read(InputStream instream) {StringBuilder sb = null;try {

sb = new StringBuilder();BufferedReader r = new BufferedReader(new InputStreamReader(

instream));for (String line = r.readLine(); line != null; line = r.readLine()) {

sb.append(line);}

instream.close();

} catch (IOException e) {}return sb.toString();

}

}

Figure 10 shows the directory structure of the Android client application. (View a

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 20 of 29

Page 21: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 21/29

 

larger version of Figure 10.)

Figure 10. Directory structure of the Android application

Running the Android client

Now you're ready to run the Android client to invoke the JAX-RS web service and

output the XML message. Right-click on the AndroidJAXRSClient project andselect Run As > Android Application, as in Figure 11.

Figure 11. Run the Android JAX-RS client

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 21 of 29

Page 22: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 22/29

 

The Android AVD starts and the JAX-RS client application installs on the Androiddevice, as in Figure 12.

Figure 12. Android JAX-RS client installed on Android

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 22 of 29

Page 23: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 23/29

 

The AndroidJAXRSClient activity starts, and the XML message produced by theJAX-RS web service resource is output to the Android device, as in Figure 13.

Figure 13. Output XML message to Android device

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 23 of 29

Page 24: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 24/29

 

Similarly, the HTML message is the output if the method that produces thetext/html media type is uncommented in the resource class and the Accept

header is set to receive the same media type. For example, in the resource class,uncomment the method in Listing 23.

Listing 23. Produce HTML in resource class

@GET@Produces("text/html")public String getHTMLMessage() {

return "<html> " + "<title>" + "Hello Android" + "</title>"+ "<body><h1>" + "Hello Android" + "</body></h1>" + "</html> ";

}

In the client class, uncomment the addHeader invocation in Listing 24.

Listing 24. Set media type to Accept

request.addHeader("Accept", "text/html");

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 24 of 29

Page 25: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 25/29

 

Rerun the AndroidJAXRSClient application to get the HTML response, as inFigure 14.

Figure 14. HTML output to Android device

To get the text response, uncomment the method in the resource class in Listing 25.

Listing 25. Produce text media type in the resource class

@GET

@Produces("text/plain")public String getClichedMessage() {return "Hello Android";

}

In the client class, uncomment the following Accept header media type setting inListing 26.

Listing 26. Set Accept Header

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 25 of 29

Page 26: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 26/29

 

request.addHeader("Accept", "text/plain");

Rerun the AndroidJAXRSClient application to get the text message output, as inFigure 15.

Figure 15. Output text message to Android device

Summary

In this article, you learned how to create a JAX-RS web service and invoke the webservice from an Android client. You sent XML, HTML, and text output to the Androiddevice.

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 26 of 29

Page 27: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 27/29

 

Downloads

Description Name Size Downloadmethod

Sample code scripts from the article android-jaxrs-sourcecode.zip 852KB HTTP

Information about download methods

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 27 of 29

Page 28: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 28/29

 

Resources

Learn

• Android: Explore the tools and documentation for creating Android applications.

• IBM JAX-RS: Developer's Guide: Read more about installing a JAX-RSapplication.

• JAX-RS Selection Algorithm: Learn more about the basics of JAX-RS.

• Develop a Spring client for Android to a JAX-RS web service (Deepak Vohra,developerWorks, Aug 2011): Learn to access a RESTful web service with theSpring Android REST client.

• Android content on developerWorks: Explore articles, demos, and tutorialsabout Android.

• More articles by this author (Deepak Vohra, developerWorks, April2005-current): Read articles about Android, Ajax, PHP, XML, web services,Ruby on Rails, EJB, and other technologies.

• SOA and web services: Get articles, tutorials, standards, and other technicalresources for web services and SOA on developerWorks.

• XML area on developerWorks: Find the resources you need to advance yourskills in the XML arena, including DTDs, schemas, and XSLT. See the XMLtechnical library for a wide range of technical articles and tips, tutorials,standards, and IBM Redbooks.

• IBM XML certification: Find out how you can become an IBM-CertifiedDeveloper in XML and related technologies.

• developerWorks technical events and webcasts: Stay current with technology inthese sessions.

• developerWorks on Twitter: Join today to follow developerWorks tweets.

• developerWorks podcasts: Listen to interesting interviews and discussions forsoftware developers.

• developerWorks on-demand demos: Watch demos ranging from productinstallation and setup for beginners to advanced functionality for experienced

developers.

Get products and technologies

• Android SDK: Download the Android SDK and get started.

• Eclipse Downloads: Download Eclipse for Java EE.

• IBM product evaluation versions: Download or explore the online trials in the

developerWorks® ibm.com/developerWorks

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 28 of 29

Page 29: IBM Developer Works Android Jax Rs

5/14/2018 IBM Developer Works Android Jax Rs - slidepdf.com

http://slidepdf.com/reader/full/ibm-developer-works-android-jax-rs 29/29

 

IBM SOA Sandbox and get your hands on application development tools andmiddleware products from DB2®, Lotus®, Rational®, Tivoli®, andWebSphere®.

Discuss

• XML zone discussion forums: Participate in any of several XML-relateddiscussions.

• The developerWorks community: Connect with other developerWorks userswhile exploring the developer-driven blogs, forums, groups, and wikis.

About the author

Deepak Vohra

Deepak Vohra is a Sun Certified Java programmer, and Sun CertifiedWeb Component Developer. Deepak has published in Java Developer'sJournal and XML Journal.

Trademarks

IBM, the IBM logo, ibm.com, DB2, developerWorks, Lotus, Rational, Tivoli, andWebSphere are trademarks or registered trademarks of International BusinessMachines Corporation in the United States, other countries, or both. These and otherIBM trademarked terms are marked on their first occurrence in this information withthe appropriate symbol (® or ™), indicating US registered or common lawtrademarks owned by IBM at the time this information was published. Suchtrademarks may also be registered or common law trademarks in other countries.See the current list of IBM trademarks.

Adobe, the Adobe logo, PostScript, and the PostScript logo are either registeredtrademarks or trademarks of Adobe Systems Incorporated in the United States,and/or other countries.

Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.

Other company, product, or service names may be trademarks or service marks ofothers.

ibm.com/developerWorks developerWorks®

Develop an Apache HttpClient client for Android to a JAX-RS web service Trademarks © Copyright IBM Corporation 2011 Page 29 of 29