Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Okhttp 3.x dynamically add/remove authenticator / interceptor

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

like image 452
Marco Romano Avatar asked Jul 06 '16 04:07

Marco Romano


People also ask

What is OkHttp interceptor in Android?

Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks. In a nutshell, Interceptors function similarly to airport security personnel during the security check process.

What is OkHttp logging interceptor?

OkHttp is an interceptor which helps you to log your API calls.

Is OkHttp asynchronous?

OkHttp doesn't currently offer asynchronous APIs to receive a response body in parts.

Does retrofit use OkHttp?

It started as a component of OkHttp. Retrofit is a type-safe REST client for Java and Android application development. It consists of interfaces, classes, and methods that provide the required functionalities. JSON or XML data may be parsed and converted to POJOs (Plain Old Java Objects) using the Retrofit library.


1 Answers

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

like image 198
Yuri Schimke Avatar answered Nov 14 '22 22:11

Yuri Schimke