|
3 | 3 | import com.google.gson.Gson; |
4 | 4 | import com.google.gson.GsonBuilder; |
5 | 5 | import okhttp3.OkHttpClient; |
| 6 | +import okhttp3.Protocol; |
6 | 7 | import okhttp3.logging.HttpLoggingInterceptor; |
7 | 8 | import retrofit2.Retrofit; |
8 | 9 | import retrofit2.converter.gson.GsonConverterFactory; |
9 | 10 |
|
10 | | -public class FixerServiceGenerator { |
11 | | - private static final String BASE_URL = "https://data.fixer.io/api/"; |
12 | | - |
13 | | - private static final Gson gson = new GsonBuilder() |
14 | | - .registerTypeAdapterFactory(new FixerResponseTypeAdapterFactory()) |
15 | | - .create(); |
16 | | - |
17 | | - private static final Retrofit.Builder builder |
18 | | - = new Retrofit.Builder() |
19 | | - .baseUrl(BASE_URL) |
20 | | - .addConverterFactory(GsonConverterFactory.create(gson)); |
| 11 | +import java.util.Collections; |
21 | 12 |
|
22 | | - private static Retrofit retrofit = builder.build(); |
23 | | - |
24 | | - private static final OkHttpClient.Builder httpClient |
25 | | - = new OkHttpClient.Builder(); |
| 13 | +public class FixerServiceGenerator { |
| 14 | + protected static final String BASE_URL = "https://data.fixer.io/api/"; |
26 | 15 |
|
27 | | - private static final HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); |
| 16 | + protected OkHttpClient createHttpClient() { |
| 17 | + return new OkHttpClient.Builder() |
| 18 | + .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)) |
| 19 | + .protocols(Collections.singletonList(Protocol.HTTP_1_1)) |
| 20 | + .build(); |
| 21 | + } |
28 | 22 |
|
29 | | - public static <S> S createService(Class<S> serviceClass) { |
30 | | - return createService(serviceClass, HttpLoggingInterceptor.Level.BASIC); |
| 23 | + protected Gson createGson() { |
| 24 | + return new GsonBuilder() |
| 25 | + .registerTypeAdapterFactory(new FixerResponseTypeAdapterFactory()) |
| 26 | + .create(); |
31 | 27 | } |
32 | 28 |
|
33 | | - public static <S> S createService(Class<S> serviceClass, HttpLoggingInterceptor.Level logLevel) { |
34 | | - logging.setLevel(logLevel); |
35 | | - if (!httpClient.interceptors().contains(logging)) { |
36 | | - httpClient.addInterceptor(logging); |
37 | | - builder.client(httpClient.build()); |
38 | | - retrofit = builder.build(); |
39 | | - } |
40 | | - return retrofit.create(serviceClass); |
| 29 | + public <S> S createService(Class<S> serviceClass) { |
| 30 | + return new Retrofit.Builder() |
| 31 | + .baseUrl(BASE_URL) |
| 32 | + .addConverterFactory(GsonConverterFactory.create(createGson())) |
| 33 | + .client(createHttpClient()) |
| 34 | + .build() |
| 35 | + .create(serviceClass); |
41 | 36 | } |
42 | 37 |
|
43 | 38 | } |
0 commit comments