Reputation: 7856
I am running across weird behaviors with HttpLoggingInterceptor. I have noticed that if I use newBuilder() the logging does not work.
// 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
...
}
}
The above code snippet does not work. However, if I make my parameter a builder, everything works fine. Is using newBuilder() the incorrect way to do this?
// 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
...
}
}
Anyone have an idea as to why this is?
Upvotes: 0
Views: 511
Reputation: 6353
That's because the method newBuilder()
as the name implies, returns the new builder object and when you call build()
on it, new instance of OkHttpClient
will be returned created from the new builder.
Here is the source code:
/** 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()
method
fun build(): OkHttpClient = OkHttpClient(this)
The newBuilder adds to the attributes of the existing client so you will have a new client with both the old and new attributes.
If you want to use newBuilder()
method then you need to make use of the newly created 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
...
}
}
Upvotes: 1