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

Learn to create a Spring Android client

The Representational State Transfer (REST) software architecture is based on transferring representation of resources. A RESTful web service is a web service based on REST and the HTTP protocol and is made available as a URI path. The web service consists of methods producing messages of various media types such as XML, HTML, JSON, and text. The web service methods respond to HTTP methods GET, PUT, POST, and DELETE. The Java API for RESTful web services (JAX-RS) is defined in JSR 311, and Jersey is a reference implementation for JAX-RS.

Spring, a platform to run Java enterprise applications, provides several benefits, including increased productivity and runtime performance. Spring Android is an extension of the Spring framework that simplifies the development of Android applications. The main features of Spring Android are a REST client for Android and Auth support for accessing secure APIs.

In this article, access a RESTful web service with the Spring Android REST client.

Share:

Deepak Vohra (dvohra09@yahoo.com), Consultant, Independent

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



12 August 2011

Also available in Chinese Japanese

Overview

The article has the following sections:

  • Setting the environment
  • Creating a JAX-RS web service resource
  • Installing Maven plugins
  • Creating a Spring Android client
  • Configuring Maven plugins and dependencies
  • Configuring Android Maven goals
  • Running the Spring client Android application

Setting the environment

Frequently used acronyms

  • 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
  • SDK: Software Development Kit
  • UI: User Interface
  • URI: Uniform Resource Identifier
  • URL: Uniform Resource Locator
  • XML: Extensible Markup Language

To set the environment, complete the following tasks. (For links, see Resources.)

  • Install Eclipse IDE.
  • Install the Android Development Tools (ADT) plugin for Eclipse. The ADT plugin for Eclipse provides a set of extensions to develop Android applications in Eclipse.
  • Install the SDK Platform 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.
  • You also need to install a web server such as Tomcat or an application server, such as WebSphere or WebLogic server.
  • Download the Jersey archive jersey-archive-1.4.zip containing the Jersey jars and core dependencies. Also, download the Jersey bundle JAR jersey-bundle-1.4.jar. As Jersey is built using JDK 6.0, you also need to install JDK 6.0. Add the JAR files shown in Listing 1 to the runtime CLASSPATH of the application/web server.
    Listing 1. JAR files to add to server Classpath
    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
  • Download the Spring Android project ZIP file. Extract the ZIP file to a directory.

Creating a JAX-RS web service resource

You will create a Spring client for a JAX-RS web service resource in this section. Your JAX-RS web service will produce three different types of messages, each with a different MIME type: text/plain, text/xml, and text/html.

First, create an Eclipse project.

  1. Create a web project and add the JAX-RS facet to the project. Select File > New, and in the New window, select Web > Dynamic Web Project.
  2. Click Next. Specify a project name, and configure a new target runtime for the WebSphere, Tomcat, or WebLogic server.
  3. Select the default project settings, and click Finish.

Eclipse creates a dynamic web project and adds it to the Project Explorer.

  1. In the Project Properties window, configure the JAX-RS (REST Web Services) 1.1 project facet.
  2. In the JAX-RS Capabilities window, specify the Servlet name as JAX-RS Servlet, configure a JAX-RS Implementation Library, and add Jersey JARs to the user library.
  3. Add the Jersey JARs jersey-bundle-1.4.jar, C:\Jersey\jersey-archive-1.4\lib\asm-3.1.jar, and C:\Jersey\jersey-archive-1.4\lib\jsr311-api-1.1.1.jar.
  4. In the JAX-RS Capabilities window, specify the JAX-RS servlet class name as com.sun.jersey.spi.container.servlet.ServletContainer.

    The JAX-RS User libraries are added to the project, and the JAX-RS Servlet and the Servlet mapping are configured in web.xml.

  5. Add init-param elements for the com.sun.jersey.config.property.resourceConfigClass and the com.sun.jersey.config.property.packages init parameters.

Listing 2 shows the web.xml file.

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">
  <display-name>EclipseJAX-RS</display-name>
  <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>

Next, create a RESTful web service resource using a root resource class. The root resource class is a POJO annotated with the @PATH annotation, and it consists of at least three methods annotated with the @GET annotation, which indicates that the methods process HTTP GET requests. Specify the URI path on which the Java class is to be hosted as /helloworld. See Listing 3.

Listing 3. Resource URI path
@Path("/helloworld")
public class HelloWorldResource {...
}

Add resource methods to produce three different MIME types. Add the following methods to the resource class, and annotate each of the methods with the @GET annotation.

  • getClichedMessage(). Outputs a "Hello JAX-RS" message using MIME types text/plain.
  • getXMLMessage(). Outputs a "Hello JAX-RS" message using MIME type text/xml.
  • getHTMLMessage(). Outputs a "Hello JAX-RS" message using MIME type text/html.

Specify the return type for each of the methods as String, annotate each of the methods with the @PRODUCES, and specify a different MIME type for each of the methods. The getXMLMessage method is annotated with the @Produces("text/xml") annotation that produces an XML message. Uncomment only one of the methods annotated with the @GET method for each deployment. Listing 4 shows the root resource class.

Listing 4. JAX-RS web service resource class
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> ";
//     }

}

Figure 1 shows the directory structure of the AndroidJAX-RS client.

Figure 1. JAX-RS web service project
Screen capture of the directory structure for a JAX-RS web service resource class project

Next, run the resource class producing different types of output.

  1. Uncomment the method to be tested for each of the test runs.
  2. Test the text/plain MIME type as output.
  3. Start the application/web server if it is not already started.
  4. Right-click the resource class, and select Run As > Run on Server.

The AndroidJAX-RS application is deployed on the server.


Installing Maven plugins

You'll use Apache Maven, a software management tool, to build the Android project for a Spring client for the Android JAX-RS web service. Use the Maven Integration project to add Maven support to Eclipse. For Android application development with Maven, you need the Maven Android plugin, which you install in a later section, Configuring Maven plugins and dependencies. Maven Integration for Android Development Tools is an Eclipse plugin that adds support for Maven Integration to Android Development Tools and the Maven Android plugin.

You can install the Maven Integration to Android Development Tools from the Eclipse Marketplace.

  1. Open the Eclipse IDE and select Help > Eclipse Marketplace.
  2. On the Search tab of Eclipse Marketplace, specify m2eclipse-android in the Find field and click Go (see Figure 2).
    Figure 2. Selecting the m2eclipse-android plugin
    Screen capture of selecting the m2eclipse-android plugin (Search tab)
  3. The Search tab now lists the Maven Integration for Android Development Tools. Click Install (see Figure 3).
    Figure 3. Installing Maven Integration for Android Development Tools
    Screen capture of installing Maven Integration for Android Development Tools
  4. On the Confirm Selected Features window, select the check boxes for the Android Development Tools, Maven Integration for Android Development Tools, and Maven Integration for Eclipse features (see Figure 4). Click Next.
    Figure 4. Selecting the plugins to install
    Screen capture of selecting the plugins to install in Confirm Selected Features window
  5. Accept the terms of the license agreement, and click Finish to complete the installation of the plugin software.

    To check the installed plugins, select Help > About Eclipse and Installation Details in About Eclipse.


Creating a Spring Android client

In this section, you create an Android Spring client project for the JAX-RS web service. You create an Android project in which you create the Spring client for Android to access the JAX-RS web service.

  1. In Eclipse IDE, select File > New.
  2. In the New window, select Android > Android Project. Click Next.
  3. In the New Android Project window, specify a project name (AndroidSpring).
  4. For Build Target, select Android Platform 2.2 API 8.
  5. For Properties, specify an application name and a package name.
  6. Select the Create Activity check box, and specify the Activity class (AndroidSpring) as in Figure 5. An activity represents a user interaction, and the class extending the Activity class creates a window for a UI.
  7. Specify the minimum SDK version as 8, and click Finish as in Figure 5.
    Figure 5. Creating a Spring Android client
    Screen capture of creating a Spring Android client in the New Android Project window

The Android project consists of the following files:

  • An activity class(AndroidSpring), which extends the Activity class
  • A res/layout/main.xml file to specify the layout of the Android application
  • An AndroidManifest.xml file, which contains application configuration such as the package name, application components, processes, permissions, and the minimum API level for the Android system

In the res/layout/main.xml file, specify the layout of the Android UI components in a LinearLayout element. Specify the value of the android:orientation attribute as vertical. Create a UI in which the response from the web service is displayed as a text message.

Add a TextView element with the id "springmessage" to display the JAX-WS web service response for a method call to one of the get methods. The method invocation gets a Hello message as a response in the form of 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/springmessage"
               android:layout_width="fill_parent" 
android:layout_height="wrap_content"/>
</LinearLayout>

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

Listing 6. Adding Internet permissions
 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

Specify the minimum Android version with the uses-sdk element. The AndroidSpring activity, the intent-filter, and action are specified with the following element. Listing 7 shows the AndroidManifest.xml file.

Listing 7. Adding Internet permissions
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="android.spring" 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=".AndroidSpring" 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>

Figure 6 shows the AndroidManifest.xml file viewed in the Eclipse IDE.

Figure 6. AndroidManifest.xml viewed in the Eclipse IDE
Screen capture of AndroidManifest.xml viewed in the Eclipse IDE

Select Java Build Path. On the Libraries tab, add the spring-android-rest-template JAR file to the Java build path as in Figure 7.

Figure 7. Spring Android REST template JAR in the Java build path
Screen capture of Spring Android REST template JAR in the Java build path

org.springframework.web.client.RestTemplate implements RESTful principles and is the central class for client-side HTTP access. The org.springframework.http package contains the basic abstraction over client/server-side HTTP.

  1. In the AndroidSpring class, import the RestTemplate class and the org.springframework.http package. The AndroidSpring class extends the Activity class. The onCreate(Bundle savedInstanceState) method is invoked when the activity is first called.
  2. Define the user interface using the setContentView method and the layout resource.
     setContentView(R.layout.main);
  3. Create an Android widget TextView object using the findViewById method on the TextView element with id "springmessage" defined in the main.xml.
     TextView springmessage = (TextView) findViewById(R.id.springmessage);
  4. Create a HttpHeaders object, which represents HTTP request and response headers.
     HttpHeaders requestHeaders = new HttpHeaders();
  5. Set the media type of the body as specified by the Content-Type header. The media type should match the media type produced by the JAX-RS web service.
     requestHeaders.setContentType(new MediaType("text","plain"));
  6. Create an HTTP request entity consisting of request headers.
     HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders);
  7. Create a new instance of the RestTemplate using the constructor with the default settings.
     RestTemplate restTemplate = new RestTemplate();
  8. Specify the URL to the resource hosted on the URI path /helloworld.
    String url = "http://192.168.1.68:7001/AndroidJAX-RS/jaxrs/helloworld";
  9. Invoke the HTTP method to the specified URI template by sending the request entity to the request using the exchange method. The exchange method returns the response as ResponseEntity.
    ResponseEntity<String> responseEntity = 
    restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
  10. Retrieve the response String from the ResponseEntity using the getBody method.
    ResponseEntity<String> String result = responseEntity.getBody();
  11. Set the String message on the TextView UI component.
    springmessage.setText(result);

Listing 8 shows the AndroidSpring class.

Listing 8. AndroidSpring class
package anrdoid.spring;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;


public class AndroidSpring extends Activity {
    /** Called when the activity is first created. */
    @Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView 
springmessage = (TextView) findViewById(R.id.springmessage);
      //  RestTemplate restTemplate = new RestTemplate();
      //  String url = 

"http://192.168.1.68:7001/AndroidJAX-RS/jaxrs/helloworld";
      //  String result = restTemplate.getForObject(url, String.class);

        HttpHeaders 
requestHeaders = new HttpHeaders();
       requestHeaders.setContentType(new MediaType("text","xml"));
       HttpEntity<String> requestEntity = new HttpEntity<String>(requestHeaders);
        String url = "http://192.168.1.68:7001/AndroidJAX-RS/jaxrs/helloworld";
        RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = 
restTemplate.exchange(url,  HttpMethod.GET, requestEntity, String.class);
       String result = 
responseEntity.getBody();
        springmessage.setText(result);

    }
}

Configuring Maven plugins and dependencies

The configuration detail used by Maven to build a project is specified in pom.xml, which defines the Project Object Model for Maven. Project dependencies, repositories, and plugins are some of the configuration detail specified in the pom.xml file. You'll configure the following repositories, dependencies, and plugins in pom.xml.

  • Spring Maven repository - Obtains Spring 3 artifacts with Maven
  • Spring Maven Milestone Repository - Enables developing with latest Spring milestone
  • Maven Android plugin - A Maven plugin for Android
  • Maven compiler plugin - Compiles sources for a project
  • Google Android dependency - Specifies dependency on the Google Android platform
  • Spring Android REST Template Module dependency - Specifies dependency on the spring-android-rest-template

First create a pom.xml in the AndroidSpring web project.

  1. Select File > New.
  2. In the New window, select XML > XML File, and click Next
  3. In the New XML File wizard, select the AndroidSpring folder.
  4. Specify File Name as pom.xml as in Figure 8. Click Next.
    Figure 8. Creating pom.xml
    Screen capture of creating the pom.xml file
  5. Select Create XML File from an XML template, and click Next.
  6. Select the xml declaration template, and click Finish.

    The SpringAndroid project now display the pom.xml configuration file, as in Figure 9.

    Figure 9. pom.xml
    Screen capture of the pom.xml file in the SpringAndroid project

Configure the plugins, repositories, and dependencies listed earlier. To specify the Spring Maven Snapshot Repository, set the following values (see Listing 9):

  • In the <id> element, specify org.springframework.maven.snapshot
  • In the <url> element, specify http://maven.springframework.org/snapshot
  • In the enabled element for releases, set the value to false
  • In the enabled element for snapshots, set the value to true
Listing 9. Spring Maven Snapshot Repository
<repository>
     <id>org.springframework.maven.snapshot</id>
     <name>Spring Maven Snapshot Repository</name>
     <url>http://maven.springframework.org/snapshot</url>
          <releases>
               <enabled>false</enabled>
          </releases>
          <snapshots>
               <enabled>true</enabled>
          </snapshots>
</repository>

Similarly, configure the Spring Maven Milestone Repository with the following values:

  • In the id element, specify org.springframework.maven.milestone
  • In the releases/enabled element, specify true
  • In the enabled element for snapshots, set the value as false

Configure the Maven Android plugin with the values in Listing 10:

  • In the groupId element, specify com.jayway.maven.plugins.android.generation
  • In the artifactId element, specify maven-android-plugin
  • In the <configuration>element for the Maven Android plugin, specify the SDK platform as 8 and the path to the SDK as C:/Android/android-sdk
  • In the <emulator> element for the Maven Android plugin, specify the <avd> to be used.
Listing 10. Spring Maven Snapshot Repository
<plugin>
     <groupId>com.jayway.maven.plugins.android.generation2</groupId>
          <artifactId>maven-android-plugin</artifactId>
                    <version>2.8.3</version>
                    <configuration>
                         <sdk>
                    <platform>8</platform>
                         <path>C:/Android/android-sdk</path>
                         </sdk>
                         <emulator>
                              <avd>rhoAndroid30</avd>
                         </emulator>
               <deleteConflictingFiles>true</deleteConflictingFiles>
               <undeployBeforeDeploy>true</undeployBeforeDeploy>
                    </configuration>
                    <extensions>true</extensions>
</plugin>

In the <dependencies> element, configure the Google Android dependency with <artifactId> as android. Configure <dependency> element on the Spring Android REST Template Module with <artifactId> as spring-android-rest-template. Listing 11 lists the pom.xml configuration file.

Listing 11. pom.xml
<project
     xsi:schemaLocation=
     "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
     xmlns=
     "http://maven.apache.org/POM/4.0.0" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <modelVersion>4.0.0</modelVersion>
     <groupId>anrdoid.spring</groupId>
     <artifactId>spring-demo</artifactId>
     <name>Spring Demo</name>
     <packaging>apk</packaging>
     <version>1.0</version>

     <repositories>         
          <repository>
               <id>org.springframework.maven.snapshot</id>
               <name>Spring Maven Snapshot Repository</name>
               <url>http://maven.springframework.org/snapshot</url>
               <releases>
                    <enabled>false</enabled>
               </releases>
               <snapshots>
                    <enabled>true</enabled>
               </snapshots>
          </repository><!-- For developing against latest Spring milestones -->
          <repository>
               <id>org.springframework.maven.milestone</id>
               <name>Spring Maven Milestone Repository</name>
               <url>http://maven.springframework.org/milestone</url>
               <snapshots>
                    <enabled>false</enabled>
               </snapshots>
          </repository>
     </repositories>
     <build>
          <sourceDirectory>src</sourceDirectory>
          <finalName>${project.artifactId}</finalName>
          <plugins>
               <plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
               <artifactId>maven-android-plugin</artifactId>
               <version>2.8.3</version>
               <configuration>
                    <sdk>
                         <platform>8</platform>
                         <path>C:/Android/android-sdk</path>
                         </sdk>
                         <emulator>
                              <avd>rhoAndroid30</avd>
                         </emulator>
               <deleteConflictingFiles>true</deleteConflictingFiles>
                         <undeployBeforeDeploy>true</undeployBeforeDeploy>
                    </configuration>
                    <extensions>true</extensions>
               </plugin>
               <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.3.2</version>
               </plugin>
          </plugins>
     </build>
     <dependencies>
          <dependency>
               <groupId>com.google.android</groupId>
               <artifactId>android</artifactId>
               <version>2.2.1</version>
               <scope>provided</scope>
          </dependency>
          <dependency>
               <groupId>org.springframework.android</groupId>
               <artifactId>spring-android-rest-template</artifactId>
               <version>1.0.0.BUILD-SNAPSHOT</version>
          </dependency>
     </dependencies>
</project>

Specify additional dependencies and other elements from the XML schema for pom.xml (http://maven.apache.org/xsd/maven-4.0.0.xsd) as required. Now that you have configured the Maven Android plugin, the Android dependency, the Spring Android REST Template dependency, the Maven Integration for Eclipse plugin, and Maven Integration for Android Development Tools, you can use Maven to develop Android applications with a Spring client in Eclipse. But, Maven's integration with Eclipse is not complete yet. You need to enable the dependency management, which is provided by the Maven Integration for Eclipse plugin. Right-click the AndroidSpring project, and select Maven > Enable Dependency Management. See Figure 10.

Figure 10. pom.xml
Screen capture of pom.xml in Elicpse with menu pointing to Maven > Enable Dependency Management

The required Maven dependencies and sources from Maven repositories are downloaded and updated, and the project is built. The target folder is added to the SpringAndroid directory.


Configuring Android Maven goals

The Maven 2.0 build lifecycle consists of various build phases. Table 1 lists and describes the phases of the default build cycle.

Table 1. Default build cycle phases
PhaseDescription
validateValidates the project
compileCompiles the project source code
testTests the compiled source code with a unit testing framework
packagePackages the compiled code
integration-testRuns integration tests
verifyVerifies the validity of the packaging
installInstalls the packaging into the local repository
deployIn an integration and release environment, copies the package to a remote repository

When you invoke a build phase, you also invoke all the preceding build phases. A build phase consists of goals, which represent finer-grained specific tasks. A build phase might be associated with zero or more goals. If a build phase does not have any goals bound to it, the build phase does not run. Goals are assigned to build phases with packaging and plugins. Set the packaging to apk in pom.xml:

<packaging>apk</packaging>

Based on the packaging type specified, specific goals are bound to the different build phases. Some packaging types are available from plugins configured in pom.xml. The apk packaging type is available with the Maven Android plugin. You configured the Maven Android plugin in pom.xml. To use the packaging type associated with the Maven Android plugin, set the extensions element to true as in Listing 12.

Listing 12. pom.xml
 <plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>maven-android-plugin</artifactId>
......
<extensions>true</extensions>
</plugin>

You can also add goals by configuring plugins in pom.xml. Each plugin provides some goals whose configuration, such as binding to a specific build phase, can be configured in pom.xml. With the packaging type apk, the Maven Android plugin customizes the default Maven lifecycle and runs some additional tasks. Table 2 lists and describes those customizations to the default Maven lifecycle.

Table 2. Customizations to the default Maven phases
Maven phaseDescription
generate-sourcesPackages the Android-specific resources, such as AndroidManifest.xml, using the Android Asset Packaging Tool (AAPT)
process-classesConverts all classes (libraries, resources, and project code) into davlik executable format using the dx tool
packageCreates the Android package file (Apk) using the Android package tool (apk) for installation on an emulator or device
pre-integration-test Deploys the Android package file (apk) including dependencies to the emulator or device
integration-testRuns the instrumentation test classes against the deployed application

Table 3 lists and describes the goals that the Maven Android plugin provides.

Table 3. Maven Android plugin goals
GoalDescription
android:apkCreates the Android package file (apk).
android:deployDeploys the built (or another) apk to emulator or device.
android:deploy-dependenciesDeploys all dependencies of type apk.
android:dexConverts Java classes to Android Dalvik Executable (dex) format.
android:emulator-startStarts the Android emulator. You have configured an emulator for the Maven Android plugin in pom.xml:
<emulator><avd>rhoAndroid30</avd></emulator> You can also configure the start up parameters and options in the emulator element.
android:generate-sourcesStops the Android emulator.
installGenerates the R.java file and deletes any R.java in the source directory. Generates Java files based on .aidl files and deletes any .java files with the same name as an .aidl file.
android:instrumentRuns the instrumentation Android package on the emulator/device.
android:internal-integration-testIs an internal goal associated with the integration-test phase.
android:internal-pre-integration-testIs an internal goal associated with the pre-integration-test phase.
android:pullCopies files and directories from the emulator or device.
android:pushCopies files and directories to the emulator or device.
android:undeployUndeploys the apk associated with the current build project, or another specified apk, from the emulator or device.

Next, you configure some goals from the Maven Android plugin into the Maven lifecycle. Right-click AndroidSpring, and select Run As > Maven build as in Figure 11.

Figure 11. Configuring a Maven-run configuration
Screen capture of configuring a Maven-run configuration

In the Maven Build node, add a Run Configuration for the android:emulator-start goal. Specify a Run Configuration name (AndroidSpring), and specify the android:emulator-start in Goals as in Figure 12. Maven Runtime is the Embedded 3.0-Snapshot. Click Apply.

Figure 12. Configuring the android:emualtor-start goal
Screen capture of configuring the android:emualtor-start goal

Similarly, configure another Run Configuration (AndroidSpring(2)). In Goals, specify the following Maven build phases and Maven Android plugin goal.

clean package android:deploy

The build phases (and any preceding build phases for each build phase lifecycle) and goals are invoked in the order specified. Figure 13 shows the Run Configuration AndroidSpring (2).

Figure 13. Run configuration to package and deploy the Spring client
Screen capture of the run configuration to package and deploy the Spring client

Running the Spring client Android application

Next, run the Android Spring application. Right-click AndroidSpring, and select Run As > Android Application as in Figure 14.

Figure 14. Running the Spring Android application
Screen capture of running the Spring Android application

The Maven configurations that you configured are listed. First, select the configuration to start the Android emulator as in Figure 15. Click OK.

Figure 15. Starting the Android emulator
Screen capture of starting the Android emulator

Subsequently, select the configuration to deploy the Android apk file. The AndroidSpring application is packaged as an apk and then deployed to the Android emulator. Figure 16 shows the AndroidSpring application in the Android emulator.

Figure 16. Spring Android client application
Screen capture of the Spring Android client application

Click the AndroidSpring application to run the application. The Spring client for the JAX-RS web service invokes the web service, and the message returned by the web service displays in the Android emulator as in Figure 17.

Figure 17. Text response from running the Spring Android client
Screen capture of the text response from running the Spring Android client

Modify the JAX-RS web service resource class to produce a text/xml message instead of a text/plain message. See Listing 13.

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

Modify the SpringAndroid client application to set the request headers content type to text/xml. See Listing 14.

Listing 14. Setting request headers to text/xml
 requestHeaders.setContentType(new MediaType("text","xml"));

Redeploy the AndroidJAX-RS web service resource class, and redeploy the SpringAndroid client application. Run the SpringAndroid application on the emulator to output the XML message received from the JAX-RS web service as shown in Figure 18.

Figure 18. text/xml response in Android with the Spring Android client
Screen capture of the text/xml response in Android with the Spring Android client

In this article, you created a Spring client for an JAX-RS web service using the Spring Android plugin.


Download

DescriptionNameSize
Spring Android Client Eclipse Projectandroid-spring.zip627KB

Resources

Learn

Get products and technologies

  • Android SDK: Download this SDK for the tools, sample code, and docs.
  • Spring Android: Download and start using the Spring Framework in a Android environment.
  • Eclipse for Java EE: Download the latest version of tools for creating Java EE and web applications, including a Java IDE, tools for Java EE, JPA, JSF, Mylyn and others.
  • Jersey: Download the Jersey bundle and the Jersey archive.
  • JDK 6.0: Download the JDK 6.0 binaries.
  • WebSphere Application Server: Download a Java EE 5 certified, EJB 3.0 supported technology-based application platform, that drives business agility with an innovative, performance based foundation for your SOA environment on the broadest range of platforms in the industry.
  • IBM product evaluation versions: Download or explore the online trials in the IBM SOA Sandbox and get your hands on application development tools and middleware products from DB2®, Lotus®, Rational®, Tivoli®, and WebSphere®.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Open source, Web development
ArticleID=751860
ArticleTitle=Develop a Spring client for Android to a JAX-RS web service
publish-date=08122011