DEV Community

Janak  bista
Janak bista

Posted on

Interceptors

Interceptors are the powerful mechanism that can monitor, rewrite, and retry API call.

We need to add a logger for each network call ,but by using interceptor we can add a logger once and it will work for each network calls.

Another use-case is caching the response of network calls to build an offline-first app.

Interceptors are of two types :

  1. Interceptors added between the Application Code (our written code) and the OkHttp Core Library are referred to as application interceptors. These are the interceptors that we add with addInterceptor().

  2. Interceptors on the network: These are interceptors placed between the OkHttp Core Library and the server. These can be added to OkHttpClient by using the addNetworkInterceptor command ().

Here’s a simple interceptor that logs the outgoing request and the incoming response.

class LoggingInterceptor implements Interceptor {
  @Override public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    logger.info(String.format("Sending request %s on %s%n%s",
        request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    logger.info(String.format("Received response for %s in %.1fms%n%s",
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
}
Enter fullscreen mode Exit fullscreen mode

**
We can add interceptor while building the OkHttpRequest object as follows :**

fun gfgHttpClient(): OkHttpClient {
    val builder = OkHttpClient().newBuilder()
        .addInterceptor(/*our interceptor*/)
    return builder.build()
}
Enter fullscreen mode Exit fullscreen mode

Keeping the response in the cache

If we want to cache the API call response so that when we call the API again, the response will come from Cache. If we have an API call from Client to Server and the Cache-Control header is enabled on the server, OkHttp Core will respect that header and cache the response that was sent from the server for a certain amount of time.

Top comments (0)