Как вызвать HttpLoggingInterceptor внутри request.newBuilder()

#android #api #kotlin #retrofit #response

Вопрос:

По мере того, как я исследовал и обнаружил, что .client(OkHttptvariableName)
используется внутри builder для печати ответа api в logcat.

Но в моем случае я не могу вызвать встроенный метод .client с помощью request.newBuilder.
Ниже приведены фрагменты моего кода.
Пожалуйста, помогите мне.

  val httpLoggingInterceptor = HttpLoggingInterceptor()
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
        val okHttpClient: OkHttpClient = OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build()


when {
            UserInfo.loginStatus -> {
                request = request.newBuilder()
                    .header("Authorization", UserInfo.token)
                    .build()
            }
            else -> {
                request = request.newBuilder()

                    .build()
            }
        }
 

Комментарии:

1. каково ваше ожидаемое поведение

2. @NehaRathore ,я хочу распечатать ответ api в Logcat.

Ответ №1:

Смотрите этот пример:

         val httpClient = OkHttpClient.Builder()

        if (BuildConfig.DEBUG) {
            val logging = HttpLoggingInterceptor()
            logging.setLevel(HttpLoggingInterceptor.Level.BODY)
            httpClient.addInterceptor(logging)
        }

        Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build()
    }
 

для получения дополнительной информации см.: https://futurestud.io/tutorials/retrofit-2-enable-logging-for-development-builds-only