如何使用 kotlin 在 android 中添加 http 日志记录拦截器和另一个拦截器?

How to add http logging interceptor along with another interceptor in android with kotlin?

我正在努力为我的改造客户端制作 2 个不同的拦截器 我已经有一个拦截器可以将我的查询 api_key 添加到请求中,我正在尝试添加

HttpLoggingInterceptor

对于相同的改造实例,有办法做到这一点吗?

这是我的代码

import com.example.tvapptest.Services.MovieService
import com.example.tvapptest.Services.ShowService
import com.example.tvapptest.Utils.Constants
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitConfig {

private val interceptor : HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
    this.level = HttpLoggingInterceptor.Level.BODY
}

private val client : OkHttpClient = OkHttpClient.Builder().apply {
    this.addInterceptor(interceptor)
}.build()


private val clientapi : OkHttpClient = OkHttpClient.Builder().apply {
    this.addNetworkInterceptor(ApiInterceptor())
}.build()

// use lazy to insure that only one instance of retrofit will be used - no duplication
private val retrofit : Retrofit by lazy {
    Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create())
        .baseUrl(Constants.BASE_URL)
         // the issue is here how can i add another interceptor to the same client here
        //.client(client)
        .client(clientapi)
        .build()
}


val movieService : MovieService by lazy {
    retrofit.create(MovieService::class.java)
}

val showService : ShowService by lazy {
    retrofit.create(ShowService::class.java)
}
}

这是我的 ApiInterceptor class

package com.example.tvapptest.Network

import com.example.tvapptest.Utils.Constants
import okhttp3.Interceptor
import okhttp3.Response

// this class is used to intercept the request and add the query param api_key
class ApiInterceptor() : Interceptor {

override fun intercept(chain: Interceptor.Chain): Response {
    val original = chain.request()
    val originalHttpUrl  = original.url
    val requestBuilder = original.newBuilder().url(originalHttpUrl.newBuilder().addQueryParameter("api_key",Constants.API_KEY).build())
    return  chain.proceed(requestBuilder.build())
}
}

需要两个不同的客户有什么理由吗? 似乎只使用一个拦截器并将两个拦截器添加到同一个客户端就可以了。

这与 kotlin 中的内容类似。

OkHttpClient.Builder()
    .addInterceptor(interceptor)
    .addNetworkInterceptor(ApiInterceptor())
    .build()
}