Retrofit 2.0.0-beta1

September 6th 2015, 10:01 amCategory: Mobile 0 comments

Retrofit is one of the famous REST Client java libraries which we can use in android application and java desktop applications. 
We can combine Retrofit with Gson library to deal with any REST API.

Here we will show how can we use Retrofit 2.0.0 with GSON library by showing a simple example on Android to get user information and list of his repos from Github API.
 
At first you should setup Retrofit, Gson and GsonConverter by adding the following libraries to dependecies in gradle file:

dependencies {
 compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
 compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
 compile 'com.google.code.gson:gson:2.2.4'
}
Then we can build the POJO(Plain Old Java Object) which we will use to cast the response from the request by using http://www.jsonschema2pojo.org/. That is a very useful online tool, it convert the josn object to Java classes which use Gson library like the follwing images: 


Create a new class GitHubUser in your code, we will use on the next lines.  

Create a GithubService Interface: 
public interface GitHubService { @GET("/users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }

Now we can use Retrofit by injecting the following code in any android service which extends IntentService the following code: 
    Retrofit retrofit = new Retrofit.Builder().
                    baseUrl("https://api.github.com").
                    addConverterFactory(GsonConverterFactory.create()).
                    build();

    GitHubService gitHubService = retrofit.create(GitHubService.class);

    Call<GitHubUser> gitHubUserCall = gitHubService.getUserInfo("octocat");
    try {
        Response<GitHubUser> response = gitHubUserCall.execute();
        if (response.isSuccess()) {
            GitHubUser user = response.body();
            Log.d("User Email:", user.getEmail());
            Log.d("User Avatar URL:", user.getAvatarUrl());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }