Okhttp 3.x dynamically add/remove authenticator / interceptor
Asked Answered
E

1

11

Is it possible to add/remove Authenticators and/or Interceptors to an existing Okhttp instance? If yes, how?

Eighth answered 6/7, 2016 at 4:59 Comment(1)
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
T
8

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

Ticktack answered 6/7, 2016 at 6:38 Comment(3)
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 suitTicktack

© 2022 - 2024 — McMap. All rights reserved.