In this tutorial, I will show you how to use the retrofit 2 library.
1-Android Studio and create a new project.
2-Declare the following dependencies in your build.gradle
3-Include the Internet permission in the application.
4-Create models automatically from our JSON response data using jsonschema2pojo.
In jsonschema2pojo Select source type of JSON, annotation style of Gson, uncheck Allow additional properties, and change the class name and click on preview.
The @serilizeName annotation is needed for Gson to map the JSON keys with our fields. In keeping with Java’s camelCase naming convention for class member properties, it is not recommended to use underscores to separate words in a variable. @serilizeName helps translate between the two.
In this example, we are telling Gson that our JSON key quota_remaining should be mapped to the Java field quotaRemaining. If both of these values were the same, i.e. if our JSON key was quotaRemaining. Just like the Java field, then there would be no need for the @serilizeName annotation on the field because Gson would map them automatically.
5- Create Retrofit instance
To request API with Retrofit, we need to create an instance using the Retrofit.Builder class.
6-Creating the API interfaces.
This interface contains methods we are going to use to execute HTTP requests such as GET, POST, PUT, DELETE.
Parameters of the interface methods can have the following annotations:
|@Path||variable substitution for the API 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|
7-Creating Api Utils
Now are going to create a utility class.This class will have the base URL as a static variable and also provide the APIService interface to our application through static method.
Inside the onCreate() method of the Activity, we initialize an instance of the ApiService interface and Request.