Instructions for using the Retrofit library to call api with Android

Tram Ho

What is Retrofit?

A type-safe HTTP client for Android and Java

Retrofit is a library that parses API responses by converting API into Java Interface. Retrofit is very popular with its advantages is performance, faster execution time than AsyncTask and Volley.

However, Retrofit does not integrate any JSON converters for parsing from JSON into Java objects. Instead it comes with the following JSON conversion libraries to handle that:

  • Gson: com.squareup.retrofit: converter-gson
  • Jackson: com.squareup.retrofit: converter-jackson
  • Moshi: com.squareup.retrofit: converter-moshi

To use Retrofit we add the dependency in the build.gradle file:

I will use retrofit via an api to help get the currency rate with the request below, let’s get started!

http://apilayer.net/api/live?access_key=843d4d34ae72b3882e3db642c51e28e6&currencies=VND&source=USD&format=1

Create Model Respone

We will create a Class Model based on the JSON returned by the api

Create Interface

The annotation on the interface method and parameters will show how the request is handled.

Request Method

Each method must have HTTP Annotation that provides the request method and the URL. There are 5 built-in annotations : @GET , @POST , @PUT , @DELETE and @HEAD

Query parameter

Add the required parameters

Create implemention of interface

Make a request

Retrofit also supports many things like URL MANIPULATION, FORM ENCODED, MULTIPART, … please refer to https://square.github.io/retrofit/

Share the news now

Source : Viblo