retrofit2

Getting started with retrofit2

Remarks#

Overview :

Retrofit : Type-safe HTTP client for Android and Java by Square, Inc.

GitHub Repo : https://github.com/square/retrofit

It is one of the widely used networking library in Android. By its design it is very flexible in nature and offer wide range of plug and play feature like support for various Json Parser like GSON,Jackson,moshi , support for Rx-Java , etc

Versions#

VersionRelease Date
2.3.02017-05-13
2.2.02017-02-21
2.1.02016-06-15

Setup

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:

  1. Add internet permission in manifest.xml:
 <uses-permission android:name="android.permission.INTERNET" />
  1. Add the following to your build.gradle file:
dependencies {
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'  
}
  1. 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;
}
  1. 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 = "https://test.com"

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    
  1. Next create Interface class where define all api calls with request,response type and request params for each call .(We need to create an interface for managing url calls like GET,POST..etc.)
public interface IPlusService {
    @GET("/api/category")
    Call<CategoryModel> getAllCategory();
}
  1. Create network/request client with retrofit instance :
IPlusService requestClient = retrofit.create(IPlusService.class);
  1. Call your web-service in your 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:

  1. https://github.com/codepath/android_guides/wiki/Consuming-APIs-with-Retrofit

  2. https://www.vogella.com/tutorials/Retrofit/article.html

  3. https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/

  4. https://futurestud.io/tutorials/retrofit-getting-started-and-android-client


This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow