我在Kotlin中有以下类(class),可以为HttpUrl设置QueryParam:
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
class RequestInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
val originalHttpUrl = original.url()
val url = originalHttpUrl.newBuilder()
.addQueryParameter("api_key", "")
.build()
val request = original.newBuilder().url(url).build()
return chain.proceed(request)
}
}
它需要初始化如下:
val logger = RequestInterceptor()
另一方面,我有以下代码来设置Interceptor的日志级别:
val logger = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
Log.d("API", it)
})
logger.level = HttpLoggingInterceptor.Level.BASIC
最后,我想将Interceptor设置为OkHttpClient的客户端:
val client = OkHttpClient.Builder()
.addInterceptor(logger)
.build()
问题是:如何对
addInterceptor(logger)
同时拥有类定义和日志级别? 最佳答案
您可以使用以下代码添加多个interceptors
val client = OkHttpClient.Builder().build()
client.interceptors().add(RequestInterceptor()) //<--- 1
val logger = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
Log.d("API", it)
})
logger.level = HttpLoggingInterceptor.Level.BASIC
client.interceptors().add(logger) //< --- 2