Develop an Apache HttpClient client for Android to a JAX-RS web service
2013-07-17 17:29
1101 查看
Learn to create an Apache HttpClient Android client
Summary: 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
Spring Android is another option. Learn to access a RESTful web service with the Spring Android REST client in this article, 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, lightweight, and fast. A RESTful web service exposes a set of resources identified 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 development of RESTful web services in Java.
In this article, use the Apache HttpClient library to create a JAX-RS client for Android—the popular smartphone platform. You candownload the sample
code used in this article.
Back to top
Setting up the environment
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 the environment. See Resources for links.
Install Eclipse.
Install the Android Development Tools (ADT) plug-in for Eclipse, which provides a set of extensions to develop Android applications in Eclipse.
Install the SDK Platform for Android 2.2.The Android SDK provides tools for developing Android applications.
Create an Android Virtual Device (AVD), which is an emulator for Android, in Eclipse.
Download the Jersey archive, jersey-archive-1.4.zip, containing the Jersey JARs and core dependencies. Download the Jersey bundle JAR jersey-bundle-1.4.jar.
Jersey is built using JDK 6.0, so you also need to install JDK 6.0.
Install a web server such as Tomcat, or an application server such as WebSphere®, or WebLogic server. Add the Jersey JAR files in Listing 1 to
the runtime
Listing 1. Jersey JAR Files
Back to top
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.
Select File > New, and in the New window, select Web > Dynamic Web Project. Click Next.
Specify a Project name (for example, AndroidJAX-RS) and click New Runtime, to configure a new target runtime for your WebSphere, Tomcat, or WebLogic server. Figure
1 shows the completed Dynamic Web Project window.
Figure 1. Configure a new runtime
In the New Server Runtime Environment window, select a server, such as the Tomcat server, the WebSphere server, or the WebLogic server. Click Next, as in Figure
2.
Figure 2. Select an application or web server
In the New IBM WebSphere v6.0 Runtime window, configure a JRE and the IBM WebSphere Installation Directory. ClickNext in the Dynamic Web Project dialog. Select the default Java settings for Source folder and Output folder, and clickNext.
Specify Context root as
A Dynamic Web Project is created and gets added to Project Explorer. Right-click on the project node and selectProperties.
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
In the JAX-RS Capabilities window, specify a Servlet name (JAX-RS Servlet) and configure a JAX-RS Implementation library. Select Type as User Library and click Manage.
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 user library. 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.jar
Click OK.
Figure 4. Add Jersey JAR files
In the JAX-RS Capabilities window, specify the JAX-RS servlet class name as
5. Click OK.
Figure 5. Specify the JAX-RS servlet class
In the Project Facets window, click Apply as in Figure 6, then click OK.
Figure 6. Apply the JAX-RS Project Facet
The targeted runtimes are configured with the JAX-RS project facet. Click OK in the Properties dialog.
The JAX-RS User libraries get added to the project, and the JAX-RS servlet and servlet mapping get configured in web.xml. You need to add
the
Listing 2. web.xml
Back to top
Creating and running a resource class
The next step is to create a RESTful web service resource using a root resource class. A root resource class is a POJO annotated with the
or
Select File > New > Other. In the New dialog, select Java > Class, and click Finish.
In the New Java Class window, as in Figure 7, specify:
A Source folder:
Package:
Class name:
Click Finish.
Figure 7. Create the resource class
Annotate the Java class with the
on which the Java class shall be hosted as
Listing 3. Annotate resource class with @Path
To add resource methods to produce three different MIME types, add the
Annotate each method with the
methods. Annotate each method with the
Now you want to output a "Hello JAX-RS" method using the MIME types
is annotated with the
If no other distinguishing path component is specified, the
JAX-RS selection algorithm is used to select the resource method. For example, you can specify multiple methods with the
for the methods annotated with
Listing 4. HelloWorldResource.java
Run the resource class to produce different types of output. Comment out the methods that are not to be tested, and keep one method uncommented for each of the test runs. First, test the
Start the application/web server if not already started. Right-click on the resource class and select Run As > Run on Server, as in Figure
8.
Figure 8. Run the resource class
On the server, the init parameter
initiated as
module deploys on the server.
Back to top
Creating an Android client project
In this section you'll create an Android project in which you create the JAX-RS client for Android.
In the Eclipse IDE, select File > New. In the New dialog, select Android > Android Project, then click Next.
Complete the fields in the New Android Project window, as in Figure 9.
Project name:
Build Target: Android Platform 2.2 API 8
Properties: Application name
Select Create Activity, and specify Activity class
An activity represents a user interaction, and the class extending the Activity class creates a window for a UI.
Minimum SDK Version:
Click Next
Figure 9. Create the JAX-RS client class
The files in the Android project are:
An activity class (
The res/layout/main.xml file to specify the layout of the Android application
The AndroidManifest.xml file, which contains application configuration information 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
the response from the web service is displayed as a text message. Add a
to one of the
5 shows the main.xml file:
Listing 5. main.xml
To access the JAX-RS web service from an Android device, enable the
in Listing 6.
Listing 6. Set INTERNET permission
Specify the minimum Android version with the
specified with the
Listing 7. AndroidManifest.xml
The Android SDK includes the Apache HttpClient library. Import the classes in Listing 8 into
Listing 8. Apache HttpClient library
The
the activity is first called. Define the user interface using the
9.
Listing 9. Define the UI
Listing 10 shows how to create an Android widget
on the
Listing 10. Create an Android widget
The default implementation of
11.
Listing 11. Create an HttpClient
Create an
URL to the resource hosted on the URI path
the JAX-RS web service runs (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
Specify acceptable media types using the
In the first run, set the
13.
Listing 13. Set the Accept Header
Test the output of each of the response types (plain text, html, and XML). The accepted response type should match the MIME type produced in the resource class. The MIME type produced by the resource class should match an acceptable MIME type. If the produced
MIME type and the acceptable MIME type do not match, a
the produced MIME type to
14, invoke the
Listing 14. Get the HttpResponse
From the
15).
Listing 15. Get the HttpEntity
Get the content as an
16).
Listing 16. Create an
Create a
Listing 17. Create a StringBuilder
Create a
18).
Listing 18. Create a BufferedReader
Read each line from the
19).
Listing 19. Read the BufferedReader
Get the
20).
Listing 20. Get the StringBuilder message
Set the
21).
Listing 21. Set the StringBuilder message
Listing 22 shows the
Listing 22. AndroidJAXRSClient.java
Figure 10 shows the directory structure of the Android client application. (View a larger
version of Figure 10.)
Figure 10. Directory structure of the Android application
Back to top
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 theAndroidJAXRSClient project and select Run As > Android Application, as in Figure
11.
Figure 11. Run the Android JAX-RS client
The Android AVD starts and the JAX-RS client application installs on the Android device, as in Figure 12.
Figure 12. Android JAX-RS client installed on Android
The
13.
Figure 13. Output XML message to Android device
Similarly, the HTML message is the output if the method that produces the
receive the same media type. For example, in the resource class, uncomment the method in Listing 23.
Listing 23. Produce HTML in resource class
In the client class, uncomment the
Listing 24. Set media type to Accept
Rerun the
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
In the client class, uncomment the following
Listing 26. Set Accept Header
Rerun the
Figure 15. Output text message to Android device
Back to top
Summary
In this article, you learned how to create a JAX-RS web service and invoke the web service from an Android client. You sent XML, HTML, and text output to the Android device.
原文地址:http://www.ibm.com/developerworks/library/x-android-jax-rs/#resources
PS:最近对REST比较感兴趣,特别是通过Android去调用REST的Web服务,于是找到这篇文章,获益匪浅。
按着例子做,最后是可以成功的,但是前面Eclipse环境和Jersey的配置需要自己额外操作,
我的Android项目部署在Eclipse SDK4.2.2,而Web服务部署在Eclipse Java EE IDE for Web Developers+Tomcat6.0
如果你对这块配置不熟悉,可以留言!
Summary: 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 service with the Spring Android REST client in this article, 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, lightweight, and fast. A RESTful web service exposes a set of resources identified 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 development of RESTful web services in Java.
In this article, use the Apache HttpClient library to create a JAX-RS client for Android—the popular smartphone platform. You candownload the sample
code used in this article.
Back to top
Setting up the environment
Frequently used abbreviations
API: Application programming interfaceHTML: 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 the environment. See Resources for links.
Install Eclipse.
Install the Android Development Tools (ADT) plug-in for Eclipse, which provides a set of extensions to develop Android applications in Eclipse.
Install the SDK Platform for Android 2.2.The Android SDK provides tools for developing Android applications.
Create an Android Virtual Device (AVD), which is an emulator for Android, in Eclipse.
Download the Jersey archive, jersey-archive-1.4.zip, containing the Jersey JARs and core dependencies. Download the Jersey bundle JAR jersey-bundle-1.4.jar.
Jersey is built using JDK 6.0, so you also need to install JDK 6.0.
Install a web server such as Tomcat, or an application server such as WebSphere®, or WebLogic server. Add the Jersey JAR files in Listing 1 to
the runtime
CLASSPATHof 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.
Select File > New, and in the New window, select Web > Dynamic Web Project. Click Next.
Specify a Project name (for example, AndroidJAX-RS) and click New Runtime, to configure a new target runtime for your WebSphere, Tomcat, or WebLogic server. Figure
1 shows the completed Dynamic Web Project window.
Figure 1. Configure a new runtime
In the New Server Runtime Environment window, select a server, such as the Tomcat server, the WebSphere server, or the WebLogic server. Click Next, as in Figure
2.
Figure 2. Select an application or web server
In the New IBM WebSphere v6.0 Runtime window, configure a JRE and the IBM WebSphere Installation Directory. ClickNext in the Dynamic Web Project dialog. Select the default Java settings for Source folder and Output folder, and clickNext.
Specify Context root as
AndroidJAX-RS, select the default Content Directory, and click Finish.
A Dynamic Web Project is created and gets added to Project Explorer. Right-click on the project node and selectProperties.
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
In the JAX-RS Capabilities window, specify a Servlet name (JAX-RS Servlet) and configure a JAX-RS Implementation library. Select Type as User Library and click Manage.
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 user library. 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.jar
Click OK.
Figure 4. Add Jersey JAR files
In the JAX-RS Capabilities window, specify the JAX-RS servlet class name as
com.sun.jersey.spi.container.servlet.ServletContainer, as in Figure
5. Click OK.
Figure 5. Specify the JAX-RS servlet class
In the Project Facets window, click Apply as in Figure 6, then click OK.
Figure 6. Apply the JAX-RS Project Facet
The targeted runtimes are configured with the JAX-RS project facet. Click OK in the Properties dialog.
The JAX-RS User libraries get added to the project, and the JAX-RS servlet and servlet mapping get configured in web.xml. You need to add
init-paramelements for the
com.sun.jersey.config.property.resourceConfigClassand
the
com.sun.jersey.config.property.packagesinit parameters. Listing 2 shows 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.com/ xml/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> </servlet-mapping> </web-app> |
Creating and running a resource class
The next step is to create a RESTful web service resource using a root resource class. A root resource class is a POJO annotated with the
@PATHannotation. It consists of at least one method annotated with the
@PATHannotation
or
@GET,
@PUT,
@POSTor
@DELETE.
Select File > New > Other. In the New dialog, select Java > Class, and click Finish.
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
Annotate the Java class with the
@PATHannotation. The code in Listing 3 specifies the URI path
on which the Java class shall be hosted as
/helloworld.
Listing 3. Annotate resource class with @Path
@Path("/helloworld") public class HelloWorldResource { ... } |
getClichedMessage(),
getXMLMessage(), and
getHTMLMessage()methods.
Annotate each method with the
@GETannotation, which indicates that the methods shall process HTTP GET requests. Specify
Stringas the return type for each of the
methods. Annotate each method with the
@PRODUCESannotation, and specify a different MIME type for each method.
Now you want to output a "Hello JAX-RS" method using the MIME types
text/plain,
text/xml, and
text/html. The
getXMLMessagemethod
is annotated with the
@Produces(
"text/xml") annotation that produces an XML message. Uncomment only one of the methods annotated with the
@GETmethod.
If no other distinguishing path component is specified, the
@GETrequest is routed to the method annotated with
@GET. If multiple methods match a request URI, the
JAX-RS selection algorithm is used to select the resource method. For example, you can specify multiple methods with the
@GETannotation by using a different
pathid
for 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 content return "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> "; // } } |
text/xmlMIME type as output.
Start the application/web server if not already started. Right-click on the resource class and select Run As > Run on Server, as in Figure
8.
Figure 8. Run the resource class
On the server, the init parameter
com.sun.jersey.config.property.resourceConfigClassis initiated as
com.sun.jersey.api.core.PackagesResourceConfigand the init parameter
com.sun.jersey.config.property.packagesis
initiated as
jaxrs, as specified in web.xml. The root resource class
jaxrs.HelloWorldResourceis found. The Jersey application v1.4 is initiated, and the AndroidJAX-RS
module deploys on the server.
Back to top
Creating an Android client project
In this section you'll create an Android project in which you create the JAX-RS client for Android.
In the Eclipse IDE, select File > New. In the New dialog, select Android > Android Project, then click Next.
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
AndroidJAXRSClientand Package name
android.jaxrs
Select Create Activity, and specify Activity class
AndroidJAXRSClient.
An activity represents a user interaction, and the class extending the Activity class creates a window for a UI.
Minimum SDK Version:
8
Click Next
Figure 9. Create the JAX-RS client class
The files in the Android project are:
An activity class (
AndroidJAXRSClient), which extends the
Activityclass
The res/layout/main.xml file to specify the layout of the Android application
The AndroidManifest.xml file, which contains application configuration information 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
LinearLayoutwith
android:orientation="vertical". You'll create a UI in which
the response from the web service is displayed as a text message. Add a
TextViewelement with id
jaxrsto display the JAX-WS web service response for a method call
to one of the
getmethods. The method invocation gets a Hello message as a response in either XML, HTML, or text. Listing
5 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> |
android.permission.INTERNETpermission, in AndroidManifest.xml, which allows applications to open network sockets. Add the
uses-permissionelement
in Listing 6.
Listing 6. Set INTERNET permission
<uses-permission android:name="android.permission.INTERNET"></uses-permission> |
uses-sdkelement. The
AndroidJAXRSClientactivity, the
intent-filter, and
actionare
specified with the
activityelement and sub-elements. Listing 7 shows the AndroidManifest.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"> <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> |
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; |
AndroidJAXRSClientclass extends the
Activityclass. The
onCreate(Bundle savedInstanceState)method is invoked when
the activity is first called. Define the user interface using the
setContentViewmethod and the layout resource, as in Listing
9.
Listing 9. Define the UI
setContentView(R.layout.main); |
TextViewobject, using the
findViewByIdmethod
on the
TextViewelement, with the id
jaxrsthat was defined in main.xml.
Listing 10. Create an Android widget
TextView jaxrs = (TextView) findViewById(R.id.jaxrs); |
HttpClientis
DefaultHttpClient. Create a
DefaultHttpClientobject, as Listing
11.
Listing 11. Create an HttpClient
HttpClient httpclient = new DefaultHttpClient(); |
HttpGetobject to retrieve information from the server, as in Listing 12. Specify the
URL to the resource hosted on the URI path
/helloworld. Specify the IP address for host instead of localhost. The client runs on the Android device, and localhost for the Android device is not the host on which
the JAX-RS web service runs (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"); |
Acceptheader. Set only one of the media types, which corresponds to the media type produced in the JAX-RS web service, in the
Acceptheader.
In the first run, set the
Acceptheader to
text/xmlto output the
text/xmlresponse, 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"); |
MIME type and the acceptable MIME type do not match, a
com.sun.jersey.api.client.UniformInterfaceExceptionis generated. For example, set the acceptable MIME type to
text/xmland
the produced MIME type to
application/xml. The
UniformInterfaceExceptionis generated. As in Listing
14, invoke the
execute()method of the
HttpClient, with the
HttpGetmethod as an argument, to retrieve the
HttpResponseobject.
Listing 14. Get the HttpResponse
HttpResponse response = httpclient.execute(request); |
HttpResponseobtain the
HttpEntityusing the
getEntitymethod (Listing
15).
Listing 15. Get the HttpEntity
HttpEntity entity = response.getEntity(); |
InputStreamfrom the
HttpGetusing the
getContent()method (Listing
16).
Listing 16. Create an
InputStreamfrom the
HttpEntity
InputStream instream = entity.getContent(); |
StringBuilderfor the message returned from the JAX-RS web service (Listing 17).
Listing 17. Create a StringBuilder
StringBuilder sb = new StringBuilder(); |
BufferedReaderfrom the
InputStream(Listing
18).
Listing 18. Create a BufferedReader
BufferedReader r = new BufferedReader(new InputStreamReader(instream)); |
BufferedReaderand 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); } |
Stringmessage from the
StringBuilderand close the
InputStream(Listing
20).
Listing 20. Get the StringBuilder message
String jaxrsmessage = sb.toString(); instream.close(); |
Stringmessage on the
TextViewUI component (Listing
21).
Listing 21. Set the StringBuilder message
jaxrs.setText(jaxrsmessage); |
AndroidJAXRSClientclass.
Listing 22. AndroidJAXRSClient.java
package android.jaxrs; |
version of Figure 10.)
Figure 10. Directory structure of the Android application
Back to top
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 theAndroidJAXRSClient project and select Run As > Android Application, as in Figure
11.
Figure 11. Run the Android JAX-RS client
The Android AVD starts and the JAX-RS client application installs on the Android device, as in Figure 12.
Figure 12. Android JAX-RS client installed on Android
The
AndroidJAXRSClientactivity starts, and the XML message produced by the JAX-RS web service resource is output to the Android device, as in Figure
13.
Figure 13. Output XML message to Android device
Similarly, the HTML message is the output if the method that produces the
text/htmlmedia type is uncommented in the resource class and the
Acceptheader 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> "; } |
addHeaderinvocation in Listing 24.
Listing 24. Set media type to Accept
request.addHeader("Accept", "text/html"); |
AndroidJAXRSClientapplication to get the HTML response, as in Figure 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"; } |
Acceptheader media type setting in Listing 26.
Listing 26. Set Accept Header
request.addHeader("Accept", "text/plain"); |
AndroidJAXRSClientapplication to get the text message output, as in Figure 15.
Figure 15. Output text message to Android device
Back to top
Summary
In this article, you learned how to create a JAX-RS web service and invoke the web service from an Android client. You sent XML, HTML, and text output to the Android device.
原文地址:http://www.ibm.com/developerworks/library/x-android-jax-rs/#resources
PS:最近对REST比较感兴趣,特别是通过Android去调用REST的Web服务,于是找到这篇文章,获益匪浅。
按着例子做,最后是可以成功的,但是前面Eclipse环境和Jersey的配置需要自己额外操作,
我的Android项目部署在Eclipse SDK4.2.2,而Web服务部署在Eclipse Java EE IDE for Web Developers+Tomcat6.0
如果你对这块配置不熟悉,可以留言!
相关文章推荐
- 为 Android 开发访问 JAX-RS Web 服务的 Apache HttpClient 客户端 学习创建 Apache HttpClient Android 客户端
- Android 为 Android 开发访问 JAX-RS Web 服务的 Apache HttpClient 客户端
- An HTTP & HTTP/2 client for Android and Java applications OkHttp
- HttpService & WebService For Flex Develop
- Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
- JAX-RS基础 for RESTful Web Service
- JAX-RS(Java API for RESTful Web Service)_1.1解析
- How do I set the timeout for a JAX-WS webservice client? if you want to set timeouts for specific se
- How To Write A Simple PHP/MySQL Web Service for an iOS App
- android系统内置HttpClient库(WebView+ Http(s)URLConnection(ok-http)+ HttpClient(apache-http))
- How To Write A Simple PHP/MySQL Web Service for an iOS App
- HttpService &amp; WebService For Flex Develop
- jax-rs(Java API for RESTful Web Services) 实践教程 之四 —— @Context注入HttpServletRequest 使REST保持状态!
- 求助:Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
- 为 Android 开发访问 JAX-RS Web 服务的 Apache HttpClient 客户端
- 【HTTP】Speed and Mobility: An Approach for HTTP 2.0 to Make Mobile Apps and the Web Faster
- Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
- Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
- android WebView 与 HttpClient Cookie
- Android WebView 与OkhttpClient登录状态保持一致,建立SESSION会话