android - 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
...
}
}
任何人都知道这是为什么?
解决方案
这是因为该方法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
...
}
}
推荐阅读
- iis - WS-Management 服务无法处理该请求。该服务被配置为不接受任何远程 shell 请求
- node.js - react js 类 poll 转换成 react hooks poll
- javascript - Angular 完整日历版本 5-隐藏过去的日期或禁用点击过去的日期
- html - Topnav 下拉菜单在浏览器中不起作用,但在 w3schools 编辑器中起作用?
- angular - 在 Angular 应用程序的浏览器中显示不正确
- python - Python Pip 被 sys.stderr.write(f"ERROR: {exc}") 破坏
- linux - 如何编译baremetal hello_world.c 并在qemu-system-aarch64 上运行?
- mysql - 无法运行 sql 查询
- html - 如何让我的网页根据屏幕大小进行调整?
- python - Python requests.get(url) 返回空但不知道为什么