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 callingbuilder.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 !!
Leave a Reply