首页 > 解决方案 > HttpLoggingInterceptor 不记录

问题描述

我正在使用 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
        ...
    }
}

任何人都知道这是为什么?

标签: androidinterceptorokhttp3

解决方案


这是因为该方法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
        ...
    }
}

推荐阅读