Retrofit 2 — Dynamic Endpoint-Dependent Interceptor Actions

Welcome to this tutorial with a very abstract title! OkHttp interceptors are quite great in making Retrofit even better by customizing requests (or responses) in a central place. We've used OkHttp interceptors a lot in previous tutorials (Manage Request Headers, OAuth, and many more).

A downside of the interceptors is that once you've added them to Retrofit's OkHttp client, they'll stay and be active until you manually remove them. They also always behave the same way, unless you do some funky configuration hacking.

In this tutorial, you'll learn how to fix the cumbersome behavior of an OkHttp interceptor in a less funky way.

A practical use case would be to not add authentication headers for the one or two endpoints, where you don't need them, but add authentication for all other endpoints. In this tutorial you'll learn how to implement this logic with a simple annotation on the endpoint declaration, and not some interceptor configuration code. You also will never have to add or remove the interceptor!

Retrofit Series Overview

Continue reading

University Enrollment Required

Future Students benefit from value packed videos and tutorials.

Enroll to receive exclusive content or sign in if you’re already a Future Student.

Enroll me for $12/mo

Explore the Library

Find interesting tutorials and solutions for your problems.