DEV Community

Janak  bista
Janak bista

Posted on

1 1

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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay