Guide to Retrofit.Builder API

Retrofit.Builder class uses the Builder API to allow defining the URL end point for the HTTP operations and finally build a new Retrofit instance.

Remember that calling baseUrl() is required before finally calling builder.build(). All other methods are optional.

1. Using Retrofit.Builder

A very basic example to use Retrofit.Builder class to create Retrofit instance.

private static Retrofit.Builder builder
		    	= new Retrofit.Builder()
		    		.baseUrl("https://api.domain.com/")
		    		.addConverterFactory(GsonConverterFactory.create());

private static Retrofit retrofit = builder.build();

2. Set OkHttpClient using Retrofit.Builder

Use Retrofit.Builder.client() method to set the instance of OkHttpClient in Retrofit.

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

private static Retrofit.Builder builder
	    	= new Retrofit.Builder()
	    		.baseUrl("https://api.domain.com/")
	    		.addConverterFactory(GsonConverterFactory.create())
	    		.client(httpClient.build());

private static Retrofit retrofit = builder.build();

3. Add Logging

The logging is added via interceptor to http client. An example to add HttpLoggingInterceptor to OkHttpClient.

private static HttpLoggingInterceptor logging =
        new HttpLoggingInterceptor()
                .setLevel(HttpLoggingInterceptor.Level.BODY);

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

{
	if (!httpClient.interceptors().contains(logging)) {
        httpClient.addInterceptor(logging);
    }
}

private static Retrofit.Builder builder
	    	= new Retrofit.Builder()
	    		.baseUrl("https://api.domain.com/")
	    		.addConverterFactory(GsonConverterFactory.create())
	    		.client(httpClient.build());

private static Retrofit retrofit = builder.build();

4. Conclusion

Above listed example were some commonly used cases when we need Retrofit.Builder to create Retrofit instance. There are more such cases e.g. authentication etc. We will look into them in cumming tutorials.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode