Understanding Android Networking Library — Retrofit 2
Before using any new library or framework or any technology, the three things which are needed to look into are What, Why and How.
As the documentation says, it’s a type-safe HTTP client for Android and Java.
- Easy to connect to web-services by translating the API into Java or Kotlin.
- Easy to add Headers and request types.
- Easily Customisable, you can customise it and add say any convertors like Gson, JackSon, Moshi, Prtobuf, XML etc. You can also customise it to add different interceptors and cache.
- It provides additional functionalities such as custom headers, file uploads, downloads, mocking responses (for testing).
I have created a sample weather application and will be using the same for demonstration.
Checkout the repo for full working example(retrofit_example branch)
A WeatherApplication with usage of different libraries of Android.github.com
- Add the required dependencies in apps build.gradle
2. Create the ApiClient/ApiService
Above api, is used here to get the weather data for four days. Create your own api key and add the same in the query param.
The interface ApiService, creates a method called getWeatherData with query params and GET as an endpoint.
WeatherForecast is the data class generated from json response. Any built-in plugins can be used to generate the same in android studio for both Java and Kotlin.
Few points to be noted here —
- This is where you define all the methods for different web services.
- Along with the methods, it needs the api endpoints description.Such as request type to be used and request params. Checkout here for more info for describing the api endpoints.
- The method returns the pojo class wrapped up inside the Call interface by retrofit. This is just a callback given by the retrofit to perform the request synchronously or asynchronously.
3. Create Retrofit and ApiServiceImplementation
The provideRetrofit() function, is responsible for creating an Retrofit instance.
It uses the Builder pattern and takes the BaseUrl and the Convertor for parsing json to data class and HtppClient.
Note — Retrofit 2 uses Okhttp3 under the hood, so there is no need to add additional dependency for the same.
Now, the provideApiService() returns the implementation. All you need to do is give the apiservice interface to the Retrofit and it will create the interface implementation.
Okay, So far so good…!!!
Now, the last thing need to be done is to make use of the apiservice we created.
And we are done.