Retrofit

Retrofit — A type-safe HTTP client for Android

Using this library android developer can make all network stuff much more easier.

Retrofit requires at minimum Java 7 or Android 2.3.

1. Creating New Project

  • Open build.gradle and add Retrofit, Gson dependencies.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    // retrofit, gson
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
}
  • Since we are working with network operations we need to add INTERNET permissions in AndroidManifest.xml file :

<uses-permissionandroid:name="android.permission.INTERNET"/>

—->>>>>
Structure your project under sub-packages. Create sub packages like activity, adapter, rest and model etc in your main package. Move your MainActivity under activity package.

2. Creating Model Data Class and Response Class

First, we need to know what type of JSON response we will be receiving from the HTTP or REST call.

Based on the JSON response returned from the requested API call, let’s first define how a basic data model should look like. Typically, JSON response may contain a collection(or list) of data model objects. That’s why we need separate classes for Reponse and for Data Model.

Typically, the REST call return response in JSON format. Using JsonViewer you can see JSON in more structured way. Copy the response from the API to this http://jsonviewer.stack.hu/ or https://jsonformatter.curiousconcept.com/

For example, check here: http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/

 

3. Creating the Retrofit instance (Service class)

To send network requests to an API, we need to use the Retrofit Builder class and specify the base URL for the service. So, create a class named ApiClient.java under rest package.

Here BASE_URL – it is basic URL of our API. We will use this URL for all requests later.

In Retrofit 2.0, Converter is not included in the package anymore. You need to plug a Converter in yourself.

If you want to accept json result and make it parse into DAO, you have to summon Gson Converter as a separate dependency.

Example :

public class ApiClient {
    public static final String BASE_URL = "http://api.themoviedb.org/3/";
    private static Retrofit retrofit = null;
    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

 

4. Define the Endpoints ( API calls interface)

The endpoints are defined inside of an interface using special retrofit annotations to encode details about the parameters and request method.

In addition, the return value is always a parameterized Call<T> object such as Call<MovieResponse>. For instance, the interface defines each endpoint in the following way.

Example :

public interface ApiInterface {
    @GET("movie/top_rated")
    Call<MoviesResponse> getTopRatedMovies(@Query("api_key") String apiKey);
    @GET("movie/{id}")
    Call<MoviesResponse> getMovieDetails(@Path("id") int id, @Query("api_key") String apiKey);
}

Each endpoint specifies an annotation of the HTTP method (GET, POST, etc.) and the parameters of this method can also have special annotations (@Query, @Path, @Body etc.)

Take a look to other annotations:

  • @Path – variable substitution for the API endpoint. For example movie id will be swapped for{id} in the URL endpoint.
  • @Query – specifies the query key name with the value of the annotated parameter.
  • @Body – payload for the POST call
  • @Header – specifies the header with the value of the annotated parameter