What is retrofit?
The official Retrofit page describes itself as:
A type-safe REST client for Android and Java.
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) defined for each request using anyone of the adapter/parser listed here.
For Demo purpose we would be using GSON parser
Setup:
<uses-permission android:name="android.permission.INTERNET" />
build.gradle
file:dependencies {
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
}
Create proper POJO(Model) based on your Json response:
If your json response is:
{
"CategoryModel": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
Then you can use website like JsonOnlineEditor or JsonView to format your json which will help to create your model Or use jsonschema2pojo to convert your Json to POJO using GSON annotations :
public class CategoryModel {
@SerializedName("debug")
private String debug;
@SerializedName("window")
private Window window;
@SerializedName("image")
private Image image;
@SerializedName("text")
private Text text;
}
Then we need an instance of Retrofit which acts as controller for all the request and response.
Note : We prefer to create this controller as singleton which is very helpful if we want to set some additional property of the client .
public static final String BASE_URL = "http://test.com"
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
GET
,POST
..etc.)public interface IPlusService {
@GET("/api/category")
Call<CategoryModel> getAllCategory();
}
IPlusService requestClient = retrofit.create(IPlusService.class);
Fragment/Activity
:requestClient.getAllCategory().enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<CategoryModel> call, Response<CategoryModel> response) {
// DO success handling
}
@Override
public void onFailure(Call<CategoryModel> call, Throwable t) {
// DO failure handling
}
});
Good resources:
https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
https://futurestud.io/tutorials/retrofit-getting-started-and-android-client