【问题标题】:HttpLoggingInterceptor Not LoggingHttpLoggingInterceptor 不记录
【发布时间】:2019-12-16 17:40:10
【问题描述】:

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

上面的代码 sn -p 不起作用。但是,如果我将参数设为构建器,则一切正常。使用 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
        ...
    }
}

有人知道这是为什么吗?

【问题讨论】:

    标签: android interceptor okhttp3


    【解决方案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
            ...
        }
    }
    

    【讨论】:

    • 在您的示例中, newBuilder 添加到现有客户端的属性,对吗?所以我会有一个新的客户端同时拥有新旧属性?
    • 完全正确! @portfoliobuilder
    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 2017-02-26
    • 2017-08-07
    • 2016-03-31
    • 2021-09-11
    • 1970-01-01
    • 2020-06-30
    • 2012-10-08
    相关资源
    最近更新 更多