Why Retrofit?
Before using Retrofit, I was searching for HTTP client. After using Retrofit, my work gets more easy.
Retrofit is a type-safe HTTP client for Android and Java developed by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with OkHttp.
This library makes downloading JSON or XML data from a web API fairly straightforward. Once the data is downloaded then it is parsed into a Plain Old Java Object (POJO) which must be defined for each “resource” in the response.
Comparison of Volley and Retrofit :
One Discussion | 25 Discussions | |
---|---|---|
Volley | 560ms | 4275ms |
Retrofit | 312ms | 1059ms |
Add library to project :
For Gradle:
compile 'com.squareup.retrofit:retrofit:x.x.x'
Retrofit requires at minimum Java 7 or Android 2.3.
Overview:
In Retrofit,we need to create 3 classes.
- Interface : We need to create an interface for managing URL calls like GET,POST etc. This is the service class.
@GET(“/path/{id}”) : This will call the server. Where URL is form after the BASE URL.The service calling URL will start with ‘/’ and {id} is the string retrieved from edittext.
@Path(“id”) : String ‘id’ is the string which we get from the edittext.
-
POJO (Plain Old Java Object) or Model Class : The JSON retrieved from the server is added to this class.
The JSON from server cannot be use directly in Java,so we need to use model class.
Use jsonschema2pojo.org for creating the POJO easily. -
RestAdapter Class : This is RESTClient Class. Gson is used in default for the Retrofit.You can use setup your own converter.
-
API is the Base URL.
-
We need to create a RestAdapter object with Endpoint(API) and then buid().
-
Call the function for getting the response,Callback is used for async method.We need Callback for both success request and error handling.
-
Our parsed JSON will be now in POJO. You can call each by calling each item.
Make sure to require Internet permissions in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />