Sapan Diwakar

Software developer

Follow me on Twitter Check out my code on GitHub View some of my designs on Dribbble Take a look at my Linked In profile

Accessing RESTful web services from Android

RESTful services are well suited for providing content to small footprint devices like smartphones and tablets. If you want to interact with a backend from your Android app, chances are that you will be interacting with a REST service. This post discusses some of the available REST client/frameworks available for Android and gives a small introduction to using Retrofit, a type-safe Rest client for Android and Java by Square. Let’s look at some of the options first:

  • Spring Android: If you have worked with backends with Java, you probably already know Spring. It also has an extension for Android that simplifies the development of applications that need to interact with the backend (not necessary built with Spring). It comes with a handy RestTemplate that makes it easy to make REST requests. If you use Android Annotations, it is even simpler to use.
  • Volley: This is something recently introduced at the Google IO  and isn’t exactly a REST client framework. It seems promising, but it might still be too early to start using it due to the lack of documentation and community adoption.
  • Retrofit: Its a type-safe REST client for Android and Java. If you were excited by the rest client in form of an interface (with Spring Android and Android Annotations), you will find it to be very similar. It also abstracts the rest client in form on an interface, but gives you much more control on the requests and its parameters.

One thing that I thought would be really straight forward was the ability to send arrays as url params. Now, this is something that Spring Rest Template doesn’t support out of the box. Although, it isn’t used very frequently, but when it is, you would need to modify your request urls by manually appending the array params which isn’t very clean. Retrofit, fortunately, can serialize the array into url params. And its very easy to setup the request by using annotations (even if you are not using Android Annotations) with Retrofit.

public interface MyRestClient {  
    ProductList getProducts(@Query("types[]") String[] types, @Query("category") String category);

        "Content-type: application/json"
    void createProduct(@Body Product device, Callback<Product> cb);

You can send GET, POST, PUT, DELETE, and HEAD using the annotations built-it to Retrofit. You can set the Headers for the request, supply query parameters or have the parameters in the body (which will be automatically serialized). You can have the method execute synchronously by having a return type on the method or execute the method asynchronously by passing in a callback which will be invoked with the response when the request completes.