Interceptors

janakbist

Janak bista

Posted on September 22, 2022

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.

💖 💪 🙅 🚩
janakbist
Janak bista

Posted on September 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What was your win this week?
weeklyretro What was your win this week?

November 29, 2024

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024

Modern C++ for LeetCode 🧑‍💻🚀
leetcode Modern C++ for LeetCode 🧑‍💻🚀

November 29, 2024