Tag Archives: Rest

Introduction to Android HTTP communication with Retrofit

In a previous post I described how to implement HTTP requests using the Google’s library Volley. We saw how to save lot of boilerplate code in such a critical part of our apps like the networking communication with our server using a well tested and reliable library.

We showed how straightforward is to have so useful features like parallel HTTP requests, cancel petitions, image downloads caching, etc.

But Volley is not our only option, there are more libraries out there that does a really good job,  and one of the well known and widely used is Retrofit from the Square people.  In this post you can find a very good comparison  between the two libraries where Retrofit would win as it is faster that Volley, but you better try and test by yourself and check which one would fit better on your project.

You can find here in my AndroidBootstrap project in Github how to integrate the library in an Android Studio project and a few examples of use.

 

Integration in our project

You can download the library .jar from here or if you’re using Maven:

<dependency>
 <groupId>com.squareup.okhttp</groupId>
 <artifactId>okhttp</artifactId>
 <version>2.0.0</version>
</dependency>
<dependency>
 <groupId>com.squareup.okhttp</groupId>
 <artifactId>okhttp-urlconnection</artifactId>
 <version>2.0.0</version>
</dependency>

Or if using Gradle:

compile 'com.squareup.retrofit:retrofit:1.9.0'

 

Retrofit client

The first thing we need to do is to initialise the Retrofit rest client object. You might want to use a singleton to manage the life cycle of the client if you’re planning to do frequent request on your app:

public class RestClient {

    private static final String API_URL = "http://jsonplaceholder.typicode.com";

    private static RestApi mRestApi = null;

    public static synchronized RestApi getInstance() {

        if(mRestApi == null) {

            RestAdapter adapter = new RestAdapter.Builder()
                    .setEndpoint(API_URL)
                    .build();

            mRestApi = adapter.create(RestApi.class);
        }

        return mRestApi;
    }
}

 

A simple HTTP GET request

Retrofit uses Java interfaces and annotations to define the REST API requests. Then it will generate the necessary code thto perform the HTTP requests and finally will convert the Json response in the specific pojo object using Gson.

Let’s take a look to this example:

@GET("/comments")
void getCommentsAsync(@Query("postId") String postNumber, Callback<list> callback);

As you can see “@GET” specifies the type of request and “/comments” is the path of the request.

Then we have the “@Query” annotation that specifies the addition of a param to the url which will take the value of the param “postNumber”.

Finally we can see the Callback parameter where retrofit will retrieve the object that has been created from the Json response using the Gson library.

In case we need to do a synchronous request the interface will look like this:

@GET("/comments")
List getCommentsSync(@Query("postId") String postNumber);

If we need to perform a POST operation:

@POST("/comments")
void postComment(@Body CommentItem item, Callback cb);

And if we need to add headers to our request:

@Headers("Cache-Control: max-age=640000")
@GET("/comments")
List getCommentsWithCustomHeader();

 

So this is a very brief introduction to the Retrofit library. As mentioned before you can find examples of the use and integration in my Bootstrap Android project. I’ll be adding more examples of useful libraries or snippets in the future.

And finally if you have any comment or suggestion please don’t hesitate in leave it below!

Advertisements
Tagged , , ,