Я работаю над модифицированным приложением, и я следую учебному пособию, но в учебном пособии он всегда создает следующее для каждого класса:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
Теперь я создал ретро-класс под названием APIClient, который имеет выше, плюс безопасность. Вот мой клиент API:
public class APIClient {
private static OkHttpClient.Builder httpClient;
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl("http://10.0.2.2:8080")
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceClass) {
return createService(serviceClass, null);
}
public static <S> S createService(Class<S> serviceClass, final Token token) {
if(httpClient == null){
System.out.println("client null");
httpClient = new OkHttpClient.Builder();
if (!token.getToken().contains("null")) {
System.out.println("Token not null " + token.getToken());
httpClient.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Accept", "application/json")
.header("Authorization", token.getToken())
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
}
httpClient.connectTimeout(50, TimeUnit.SECONDS);
httpClient.addInterceptor(addLogging());
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = builder.client(client).build();
return retrofit.create(serviceClass);
}
private static HttpLoggingInterceptor addLogging(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
return logging;
}
}
Сейчас в учебном пособии, за которым я следую, он делает следующее:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
Call<List<Post>> call = jsonPlaceHolderApi.getPosts();
Есть ли способ, которым я могу устранить все Retrofit retrofit = new Retrofit.Builder()
с помощью моего класс, но все еще использовать retrofit.create
часть?