What is Retrofit?
Retrofit is a REST Client for Android,By using Retrofit in Android we can easily retrieve and upload JSON ( or other structured data like RSS feed etc. ) responses from a restful web APIs. It is different from other libraries because, Retrofit gives us an easy to use platform through which we don’t need to parse JSON responses as they are done by the library itself. It uses the GSON library in background to parse the responses. All we need to do is define a POJO(Plain Old Java Object) to do all the parsing.
- Retrofit 2.0 comes with lot of features. Some of them are listed below:
Declaration for synchronous and asynchronous API calls made same.
Retrofit 2 gives Call<T> object for calling any API. Which can be canceled later on.
The converter is now excluded from Retrofit. You have to use converters of your choice separately.
It makes library very tiny Here is the list of official Converter modules provided by Square.
Choose one that fits your requirement best.
- Gson: com.squareup.retrofit:converter-gson
- Jackson: com.squareup.retrofit:converter-jackson
- Moshi: com.squareup.retrofit:converter-moshi
- Protobuf: com.squareup.retrofit:converter-protobuf
- Wire: com.squareup.retrofit:converter-wire
- Simple XML: com.squareup.retrofit:converter-simple xml
Getting Started with Retrofit 2.0
For basic understanding retrofit three classes:
POGO Classes to map structured data.
Interface class to define HTTP calls with methods.
1 . POGO class : The Simple model classes has properties, getters and setters for respective properties.
Below is the sample class for that:
2. Interface Class:
In this class methods for each Api Call define with HTTP annotation (GET, POST, etc.) to specify the request type and the relative URL,.The return value wraps the response in a Call object with the type of the expected result.
First of all, we have to specify method type we want to use for API call.
@GET , @POST , @PUT, @DELETE, @UPDATE etc.
Then we will specify Call<T> where T is response class as the return type of method.
If API requires the multipart request or FormData request then we have to specify @Multipart, @FormUrlEncoded.
In GET request or POST with JSON request does not need extra annotations
For POST(FormData) request we have to specify request as the @Field parameter.
For POST(Multipart) request we have specified request as @Part.
For POST(JSON) request we have to specify request as @Body with Request Class.
For @GET request, we can specify @Query or @Path Parameter.
Below is the sample methods for different type of request:
3. Builder Class:
Retrofit builder allows to to headers using Authentication with OkHttp interceptors, base url and converter factory etc . for the HTTP calls.
That's it now u just need to Asynchronous Call to server:
You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.