Retrofit custom interceptor

Adding custom functionality to all requests

Adding a header to all requests

For a more complete and in-depth explanation, check out our complete Retrofit course

Download the starter project here

Github repository

In this article we will see how we can add an interceptor to all requests to perform some operation.

At the same time we will learn how to add a header to all outgoing requests

Why would you want that? Let’s take a real world example, you might want to add an authentication header. When you have all the information required to authenticate your requests you want to be able to add that to every single request without adding it one by one to the functions in your api. You want to do that in one place without having to worry that if your app expands, the header will be forgotten.

Why?

While there are some standard interceptors like the one for logging, you might still want to have custom functionality that needs to be applied for all outgoing requests. An interceptor will capture any outgoing request, allow you the opportunity to perform whatever action you need, and then have the request go on its way.

You might also want to completely replace an existing request with another in certain conditions. So you have the option to intercept a request and change it completely.

How?

This is the general structure of an interceptor.

okhttpClient.addInterceptor { chain ->

    val request = chain.request()

    // do any required computation

    chain.proceed(newRequest)

}

We need to call addInterceptor on the httpClient. You will have access to the chain variable, which is the chain of execution of your request. That allows you to retrieve a lot of information about that request. For instance, you might be able to get the request specifically, do whatever processing you need, and then proceed with the chain of execution.

In this article we will implement a header for all outgoing requests. To do this, update the ApiCallService class and add the following code

okhttp3Client.addInterceptor { chain ->

    val request = chain.request()

    val newRequest = request.newBuilder()

        .addHeader(“user-agent”, “Android”)

        .build()

    chain.proceed(newRequest)

}

The okhttpClient variable should already be added to the api builder

api = Retrofit.Builder()

   

    .client(okhttp3Client.build())

   

Running the code, we can see the header added to the outgoing request.

custom interceptor

For a more complete and in-depth explanation, check out our complete Retrofit course

Close Bitnami banner
Bitnami