Knowing Android
Published in

Knowing Android

Headers, Interceptors, and Authenticators with Retrofit

The happy way

In Android sometimes you need to add a couple of parameters, like headers, to make a successful request, this is normal behavior from all the Android Apps when you are using Retrofit, you can do it in multiple ways

For example, you can add parameters directly to your request interface using the annotation Headers and putting a plain String, like this:

Another solution is to send the Headers as a parameter to your interface function, using an annotation Header and sending a parameter, this gives you the possibility to have a custom parameter that you can manage from every request:


A couple of people using Dagger probably will go for an Interceptor, you can have two types of interceptor:
The first one is using an interceptor directly in your Singleton, this will not give you versatility, but it will solve your problem faster, in this example, you can go for the chain object, get the request of the Retrofit call, get a new Builder and then add the Headers.

Or you can use this as file apart, extending Interceptor class, this will let you have the reusable code.


Imagine you want to catch the response before to go to your Observable, maybe trying to catch a specific error before hitting your Throwable, for this specific behavior you need an Authenticator.
This authenticator will catch the response, when there is an error (401 error) then we will update the AuthToken for the failed request and it will send resend the request, no need to send anything else or make any logic inside your presentation layer.

To make the implementation you only need to set this object like this:

And you re ready to go.
Happy Coding! 👩🏻‍💻

If you have questions, you can reach me here.



Android development in Spanish and English | Desarrollo de Android en Español e Ingles

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dinorah Tovar

Google Developer Expert on Android | Doing Kotlin | Making Software 24/7 | Kotlin Multiplatform | She/Her | Opinions are my own, and not my employer