-
-
Save munho/98ed64b1f8938d257d21f707e6285796 to your computer and use it in GitHub Desktop.
Retrofit2 Service Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class ServiceGenerator { | |
| private static final String API_BASE_URL = "https://api.github.com/"; | |
| private static Retrofit retrofit; | |
| private static Gson mGson = new GsonBuilder() | |
| .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'") | |
| .create(); | |
| private static Retrofit.Builder builder = new Retrofit.Builder() | |
| .baseUrl(API_BASE_URL) | |
| .addConverterFactory(GsonConverterFactory.create(mGson)); | |
| private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); | |
| private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor() | |
| .setLevel(HttpLoggingInterceptor.Level.BODY); | |
| public static <S> S createService(Class<S> serviceClass) { | |
| if (!httpClient.interceptors().contains(logging)) { | |
| httpClient.addInterceptor(logging); | |
| builder.client(httpClient.build()); | |
| retrofit = builder.build(); | |
| } | |
| retrofit = builder.client(httpClient.build()).build(); | |
| return retrofit.create(serviceClass); | |
| } | |
| /** | |
| * or Error Handing when non-OK response is received from Server | |
| */ | |
| @NonNull | |
| public static Retrofit retrofit() { | |
| OkHttpClient client = httpClient.build();; | |
| return builder.client(client).build(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment