Use CRest to consume RESTful Web Service for Android

  • Posted on: 20 April 2014
  • By: Zhijun Chen

There are several ways to consume RESTful web services from Android. One option would be using the builtin HttpClient library and parsing the response using an XML/Json parser library, e.g. Gson. After several hours research, I chose CRest Android version because of its simplicity. CRest is a lightweight JAX-RS compatible framework aiming to simplify the integration of external REST services into Java applications.

* Libraries required

The following libraries are required and should be put inside Android /libs folder. Maven dependencies are also available if you are using android maven plugin.

* RESTful Web Service Example and sample Response

Suppose we have a REST service GET call which simply returns the user with id: http://192.168.0.100:8000/api/v1/user/{id}?format=json. And the sample JSON response is given as follows.

 {
  "id": 1,
  "first_name": "Zhijun",
  "last_name": "Chen",
  "name": "zhijun.chen"
}
* Java Model Objects

A Pojo is needed to map the JSON response into Java objects.

package uk.co.zhijun.model;

import org.codehaus.jackson.annotate.JsonProperty;

public class User {
	private Long id;
	@JsonProperty("first_name")
	private String firstName;
	@JsonProperty("last_name")
	private String lastName;
	private String name;
	
	public User() {
	}
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
	
	public String getFirstName() {
		return firstName;
	}
	
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	
	public String getLastName() {
		return lastName;
	}
	
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

Note: Any properties defined inside Java model but not in the JSON response should be annotated with @JsonIgnore

* Services Interfaces

Next we will create a service interface to consume the REST service.

import org.codegist.crest.annotate.Consumes;
import org.codegist.crest.annotate.EndPoint;
import org.codegist.crest.annotate.HeaderParam;
import org.codegist.crest.annotate.Path;
import org.codegist.crest.annotate.PathParam;

import uk.co.zhijun.model.User;

@EndPoint("http://192.168.0.100:8000")
@Path("/api/v1/user")
@Consumes("application/json")
public interface UserService {
	
	@Path("/{id}")
	@HeaderParam(value="Authorization", defaultValue="Basic {basic.auth.digest}")
	public User getUser(@PathParam("id") long id);
}

The @HeaderParam is needed when you need to add any http request header to the request, in this case it is an authentication token. @Consumes defines the type of response received from REST service. We will show how to pass in {basic.auth.digest} value.

* Android Integration

Now we have service interface ready, the final step would be integrated it into Android project. Android uses a seperate thread from main thread to execute http calls. And it is recommended to set CRest to use HttpClient to send requests. The following code gives an example.

private class FetchUserTask extends AsyncTask<Void, Void, User> {

			@Override
			protected User doInBackground(Void... params) {
				String username = "username";
				String password = "password";
				String basicAuthDigest = Base64.encode(username + ":" + password);

				CRest crest = CRest.placeholder("basic.auth.digest", basicAuthDigest)
						.setHttpChannelFactory(
								HttpClientHttpChannelFactory.class).build();
				UserService userService = crest.build(UserService.class);
				User user = userService.getUser(1);
				return user;
			}

			protected void onPostExecute(User user) {
				// do something with the response
			}
		}

As you can see, the authentication code is passed in using placeholder.

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.