Skip to content

Instantly share code, notes, and snippets.

@TranBaVinhSon
Created March 7, 2018 14:03
Show Gist options
  • Save TranBaVinhSon/5bbe2b81adae1e626de4a638b8af6c8e to your computer and use it in GitHub Desktop.
Save TranBaVinhSon/5bbe2b81adae1e626de4a638b8af6c8e to your computer and use it in GitHub Desktop.
package com.example.sontbv.retrofittutorial.webservice;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by sontbv on 3/7/18.
*/
public class ServiceGenerator {
private final static String BASE_API_URL = "https://ghibliapi.herokuapp.com/";
private static Retrofit retrofit = null;
private static Gson gson = new GsonBuilder().create();
private static HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
private static OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor);
private static OkHttpClient okHttpClient = okHttpClientBuilder.build();
public static <T> T createService(Class<T> serviceClass){
if(retrofit == null){
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.baseUrl(BASE_API_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit.create(serviceClass);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment