|
| 1 | +package com.baeldung.retrofitguide; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import okhttp3.Interceptor; |
| 5 | +import okhttp3.OkHttpClient; |
| 6 | +import okhttp3.Request; |
| 7 | +import okhttp3.Response; |
| 8 | +import okhttp3.logging.HttpLoggingInterceptor; |
| 9 | +import retrofit2.Retrofit; |
| 10 | +import retrofit2.converter.gson.GsonConverterFactory; |
| 11 | + |
| 12 | +public class GitHubServiceGenerator { |
| 13 | + |
| 14 | + private static final String BASE_URL = "https://api.github.com/"; |
| 15 | + |
| 16 | + private static Retrofit.Builder builder |
| 17 | + = new Retrofit.Builder() |
| 18 | + .baseUrl(BASE_URL) |
| 19 | + .addConverterFactory(GsonConverterFactory.create()); |
| 20 | + |
| 21 | + private static Retrofit retrofit = builder.build(); |
| 22 | + |
| 23 | + private static OkHttpClient.Builder httpClient |
| 24 | + = new OkHttpClient.Builder(); |
| 25 | + |
| 26 | + private static HttpLoggingInterceptor logging |
| 27 | + = new HttpLoggingInterceptor() |
| 28 | + .setLevel(HttpLoggingInterceptor.Level.BASIC); |
| 29 | + |
| 30 | + public static <S> S createService(Class<S> serviceClass) { |
| 31 | + if (!httpClient.interceptors().contains(logging)) { |
| 32 | + httpClient.addInterceptor(logging); |
| 33 | + builder.client(httpClient.build()); |
| 34 | + retrofit = builder.build(); |
| 35 | + } |
| 36 | + return retrofit.create(serviceClass); |
| 37 | + } |
| 38 | + |
| 39 | + public static <S> S createService(Class<S> serviceClass, final String token) { |
| 40 | + if (token != null) { |
| 41 | + httpClient.interceptors().clear(); |
| 42 | + httpClient.addInterceptor(new Interceptor() { |
| 43 | + @Override |
| 44 | + public Response intercept(Interceptor.Chain chain) throws IOException { |
| 45 | + Request original = chain.request(); |
| 46 | + Request.Builder builder = original.newBuilder() |
| 47 | + .header("Authorization", token); |
| 48 | + Request request = builder.build(); |
| 49 | + return chain.proceed(request); |
| 50 | + } |
| 51 | + }); |
| 52 | + builder.client(httpClient.build()); |
| 53 | + retrofit = builder.build(); |
| 54 | + } |
| 55 | + return retrofit.create(serviceClass); |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments