Retrofit Android Example Tutorial

Welcome to Retrofit Android Example Tutorial. Today we’ll use the Retrofit library developed by Square to handle REST API calls in our android application.

Retrofit Android

Retrofit is type-safe REST client for Android and Java which aims to make it easier to consume RESTful web services. We’ll not go into the details of Retrofit 1.x versions and jump onto Retrofit 2 directly which has a lot of new features and a changed internal API compared to the previous versions.

Retrofit 2 by default leverages OkHttp as the networking layer and is built on top of it.

Retrofit automatically serialises the JSON response using a POJO(Plain Old Java Object) which must be defined in advanced for the JSON Structure. To serialise JSON we need a converter to convert it into Gson first. We need to add the following dependencies in our build.grade file.

OkHttp dependency is already shipped with Retrofit 2 dependency. If you wish to use a separate OkHttp dependency, you should exclude the OkHttp dependency from Retrofit 2 as:

  • The logging-interceptor generates a log string of the entire response that’s returned.
  • There are other converters to parse the JSON to the necessary type. A few of them are listed below.
  1. Jackson : com.squareup.retrofit2:converter-jackson:2.1.0
  2. Moshi : com.squareup.retrofit2:converter-moshi:2.1.0
  3. Protobuf : com.squareup.retrofit2:converter-protobuf:2.1.0
  4. Wire : com.squareup.retrofit2:converter-wire:2.1.0
  5. Simple XML : com.squareup.retrofit2:converter-simplexml:2.1.0

Add the permission to access internet in the AndroidManifest.xml file.

OkHttp Interceptors

Interceptors are a powerful mechanism present in OkHttp that can monitor, rewrite, and retry calls.
Interceptors can be majorly divided into two categories:

  • Application Interceptors : To register an application interceptor, we need to call addInterceptor() on OkHttpClient.Builder
  • Network Interceptors : To register a Network Interceptor, invoke addNetworkInterceptor() instead of addInterceptor()

Setting Up the Retrofit Interface

The getClient() method in the above code will be called every time while setting up a Retrofit interface. Retrofit provides with a list of annotations for each of the HTTP methods: @GET, @POST, @PUT, @DELETE, @PATCH or @HEAD.

Let’s see how our APIInterface.java class looks like.

In the above class, we’ve defined some methods that perform HTTP requests with annotation.
We’ve used a few test APIs from here

@GET("/api/unknown") calls doGetListResources();.

doGetListResources() is the method name. MultipleResource.java is a Model POJO class for our response object that’s used to map the response parameters to their respective variables. These POJO class act as the method return type.

A simple POJO class for MultipleResources.java is given below.

@SerializedName annotation is used to specify the name of the field that’s in the JSON Response.

To create a POJO class for each response, we can go to https://www.jsonschema2pojo.org/ and paste the json response structure as shown in the image below.

android-json-2-schema-450x430

Preview the POJO class and copy it into your Android Studio Project Structure.

The POJO classes are wrapped into a typed Retrofit Call class.

Note: A JSONArray is serialised a List of Objects in the POJO classes

Method Parameters : There are a wide variety of possible options of parameters to pass inside a method:

  • @Body – Sends Java objects as request body.
  • @Url – use dynamic URLs.
  • @Query – We can simply add a method parameter with @Query() and a query parameter name, describing the type. To URL encode a query use the form:
    @Query(value = "auth_token",encoded = true) String auth_token
  • @Field – send data as form-urlencoded. This requires a @FormUrlEncoded annotation attached with the method.
    The @Field parameter works only with a POST

Note: @Field requires a mandatory parameter. In cases when @Field is optional, we can use @Query instead and pass a null value.

Retrofit Android Example Project Structure

android-retrofit-project-structure

The pojo package defines four model classes for each of the API endpoint responses defined in the APIInterface.java class.

User.java

The above class is used to create the Response Body for the createUser() method

UserList.java

CreateUserResponse.java

The MainActivity.java is where we call each of the API endpoints defined in the Interface class and display each of the fields in a Toast/TextView.

apiInterface = APIClient.getClient().create(APIInterface.class); is used to instantiate the APIClient.
To map the Model class to the response we use:

MultipleResource resource = response.body();

Running the application would call each of the endpoints and display a Toast message for them accordingly.

This brings an end to Retrofit android example tutorial. You can download the Android Retrofit example project from the link below.

By admin

Leave a Reply

%d bloggers like this: