Retrofit Introduction

Internet Permission in Android’s Manifest

<uses-permission android:name=”android.permission.INTERNET”/>

Define Dependency: Gradle

dependencies {
// Retrofit & OkHttp
compile ‘com.squareup.retrofit2:retrofit:2.1.0’
compile ‘com.squareup.retrofit2:converter-gson:2.1.0’
}

Define Service Interface / API Interface :

public interface GitHubService {
@GET(“users/{user}/repos”)
Call<List<GitHubRepo>> reposForUser(@Path(“user”) String username);
}

Service Generator

This is the heart. It defines a method to create a basic REST client for a given class/interface which returns a service class from the interface.

public class ServiceGenerator {

public static String apiBaseUrl = “https://api.github.com/&#8221;;

private static Retrofit retrofit;

private static Retrofit.Builder builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(apiBaseUrl);

private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

public static void changeApiBaseUrl(String newApiBaseUrl) {
apiBaseUrl = newApiBaseUrl;

builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.client(new OkHttpClient())
.baseUrl(apiBaseUrl);
}

public static <S> S createService(Class<S> serviceClass) {

builder.client(httpClient.build());
retrofit = builder.build();

return retrofit.create(serviceClass);
}

public static Retrofit retrofit() {
return retrofit;
}
}

Retrofit’s Retrofit-Builder to create a new REST client with the given API base url (BASE_URL).

Why Is Everything Declared Static Within the Servicegenerator?

We want to use the same OkHttpClient throughout the app to just open one socket connection that handles all the request and responses including caching and many
more.

And because we use the OkHttpClient throughout this class, we need to make all fields and methods static.

It’s common practice to just use one OkHttpClient instances to reuse open socket connection.

• [x] What is Retrofit
• [x] Why use Retrofit
• [x] How to define a service interface representing an API endpoint
• [x] How to create an instance of the service interface
• [x] How to execute an API request

 

 

 

Leave a comment