我正在使用HttpLoggingInterceptor运行各种奇怪的行为。我注意到,如果我使用newBuilder(),则无法进行日志记录。
// instantiate object (in app)
val okHttpRequestManager: HttpRequestManager = OkHttpRequestManager(OkHttpClient(), null)
// execute request (in app)
okHttpRequestManager.execute(request, callback)
// another class (in request module)
open class OkHttpRequestManager(private val client: OkHttpClient,
private val httpLoggingInterceptor: HttpLoggingInterceptor?) : HttpRequestExecutor {
override fun execute(httpRequest: HttpRequest, callback: HttpResponseCallback?) {
if (httpLoggingInterceptor != null) {
client.newBuilder().addInterceptor(httpLoggingInterceptor).build()
}
// perform request below
...
}
}
上面的代码段不起作用。但是,如果我将参数设为构建器,则一切正常。使用newBuilder()是这样做的不正确方法吗?
// the below works
// another class (in request module)
open class OkHttpRequestManager(private val client: OkHttpClient.Builder,
private val httpLoggingInterceptor: HttpLoggingInterceptor?) : HttpRequestExecutor {
override fun execute(httpRequest: HttpRequest, callback: HttpResponseCallback?) {
if (httpLoggingInterceptor != null) {
// no newBuilder() or build() and works like a charm
client.addInterceptor(httpLoggingInterceptor)
}
// perform request below
...
}
}
有人知道为什么会这样吗?
答案 0 :(得分:1)
这是因为名称中所暗示的方法newBuilder()
返回了新的构建器对象,并且当您在其上调用build()
时,将返回由新的构建器创建的OkHttpClient
的新实例
这是源代码:
/** Prepares the [request] to be executed at some point in the future. */
override fun newCall(request: Request): Call {
return RealCall.newRealCall(this, request, forWebSocket = false)
}
build()
方法
fun build(): OkHttpClient = OkHttpClient(this)
newBuilder将添加到现有客户端的属性,以便您 将拥有一个同时具有新旧属性的新客户端。
如果要使用newBuilder()
方法,则需要使用新创建的OkHttpClient
。
// another class (in request module)
open class OkHttpRequestManager(private val client: OkHttpClient,
private val httpLoggingInterceptor: HttpLoggingInterceptor?) : HttpRequestExecutor {
override fun execute(httpRequest: HttpRequest, callback: HttpResponseCallback?) {
if (httpLoggingInterceptor != null) {
val newClient = client.newBuilder().addInterceptor(httpLoggingInterceptor).build()
}
// perform request below using newClient
...
}
}