Инициализация класса модернизации в другом классе - PullRequest
0 голосов
/ 09 февраля 2020

Я работаю над модифицированным приложением, и я следую учебному пособию, но в учебном пособии он всегда создает следующее для каждого класса:

       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 часть?

1 Ответ

0 голосов
/ 09 февраля 2020
public class APIClient {

    private static final String BASE_URL = "http://10.0.2.2:8080/";

    private static OkHttpClient.Builder httpClient;
    private Retrofit retrofit;




    private APIClient() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }


    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final MediaSession.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;
    }


}

Call<List<Post>> call = APIClient.createService(JsonPlaceHolderApi.class).getPosts();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...