Retrofit 2 Service Generator

Though we can easily create Retrofit instances on demand for different client in place, having a dedicated factory method or service generator method is definitely desirable.

In this service generator, we can have centralized place to add/modify the authentication, logging and error handling logic.

1. Retrofit service generator

A service generator class defines one method to create a basic REST client for a given class/interface. It simply returns a service class from the provided argument interface.

In given example, we have used the API base URL to reqres.in and added HttpLoggingInterceptor for logging support. Feel free to tweak the configuration.

All fields are declared as static in this class because in Android apps, we generally have one network request in progress at a time. Feel free to change it if your app require multiple connections at the same time.

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ServiceGenerator 
{
	private static final String BASE_URL = "https://reqres.in/";

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

	private static Retrofit retrofit = builder.build();

	private static HttpLoggingInterceptor loggingInterceptor =
            new HttpLoggingInterceptor()
                    .setLevel(HttpLoggingInterceptor.Level.BASIC);

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

	public static <S> S createService(Class<S> serviceClass) 
	{
		if (!httpClient.interceptors().contains(loggingInterceptor)) {
			 httpClient.addInterceptor(loggingInterceptor);
			 builder.client(httpClient.build());
		}
		
		return retrofit.create(serviceClass);
	}
}

2. How to use service generator

One we have create the service generator class, all we have to do is call it’s createService() method to have a functioning REST client.

import retrofit2.Call;
import retrofit2.Response;

public class UserServiceClient 
{
	public static void main(String[] args) 
	{
		UserService service = ServiceGenerator.createService(UserService.class);
		
		// Calling '/api/users/2'
		Call<UserApiResponse> callSync = service.getUser(2);
		 
		try 
		{
		    Response<UserApiResponse> response = callSync.execute();
		    UserApiResponse apiResponse = response.body();
		    System.out.println(apiResponse);
		} 
		catch (Exception ex) 
		{ 
			ex.printStackTrace();
		}
	}
}

Program output.

UserApiResponse [data=User [id=2, first_name=Janet, 
	last_name=Weaver, email=janet.weaver@reqres.in]]

Drop me your questions in comments.

Happy Learning !!

Reference: ServiceGenerator.java in retrofit-oauth

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

3 thoughts on “Retrofit 2 Service Generator”

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.