Is it possible to add/remove Authenticators and/or Interceptors to an existing Okhttp
instance? If yes, how?
Okhttp 3.x dynamically add/remove authenticator / interceptor
Asked Answered
Well, API is pretty explanatory: github.com/square/okhttp/wiki/… It shows how to add an Interceptor during okhttp instance creation. But I cannot find a way to add it afterwards without creating a new instance. –
Eighth
No, it is not possible.
However, you can create a builder from an existing client, and make changes to that. This will share the dispatcher, connectionPool etc.
OkHttpClient.Builder clientBuilder = client1.newBuilder();
clientBuilder.networkInterceptors().add(0, serviceInterceptor);
OkHttpClient client2 = clientBuilder.build();
There is an example for adjusting the timeout of a client in the javadoc https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html
Thing is I usually create okhttp as a single instance object through dependency injection, therefore it's not possible to 'swap' the single instance with another one every time I add/remove an interceptor. –
Eighth
I guess OP is referring to "an existing Okhttp instance" –
Bogie
It may not work nicely for you, but it is the answer. Sorry it doesn't suit –
Ticktack
© 2022 - 2024 — McMap. All rights reserved.