← All notes

Android

Three Retrofit Clients in One Android App with Hilt Qualifiers

Managing unauthenticated, OAuth 1.0, and Bearer token APIs in a single app requires isolated OkHttpClient instances. This post covers a Hilt qualifier pattern that eliminates injection ambiguity across all three.

Published
Reading
5 min
Author
Fidelis Uwem Joseph
Series · Part 1 of 5Android Foundations
  1. Three Retrofit Clients in One Android App with Hilt Qualifiers
  2. Encrypted Token Storage on Android with EncryptedSharedPreferences and Hilt
  3. Seeding a Room Database via ADB BroadcastReceiver in Kotlin
  4. Printing Labels from Android Using the Brother QL SDK
  5. Android Project Docs with MkDocs, Dokka, and Firebase Hosting

Series overviewPart 2 →

When your Android app talks to three different APIs — one unauthenticated, one using OAuth 1.0 signed requests, and one using a rotating JWT Bearer token — you cannot share an OkHttpClient. Each service needs its own interceptor chain. Without Hilt qualifiers, Retrofit injection collapses into an ambiguous mess. This post shows the qualifier pattern that keeps all three clients isolated, singleton, and independently testable.

Prerequisites

Kotlin 2.0, Hilt 2.56, Retrofit 2.11.0, OkHttp 4.12.0, okhttp-signpost for OAuth 1.0. The app targets minSdk 23, compileSdk 36.

Background

The app integrates three APIs:

  • BrickApp / Brickognize: image recognition API, no authentication
  • BrickLink: LEGO marketplace API, OAuth 1.0 with consumer key/secret and per-user token/token-secret
  • BrickWorks: internal service, Bearer token from encrypted SharedPreferences

Hilt’s @Provides resolution works by type. If you provide three OkHttpClient instances and three Retrofit instances with no distinguishing annotation, the compiler rejects the module with a duplicate binding error. If you get past that by accident (one module, one binding), every service gets the wrong client.

Implementation

1. Dependencies

app/build.gradle.kts
dependencies {
implementation(platform(libs.okhttp.bom))
implementation(libs.okhttp)
implementation(libs.okhttp.logging)
implementation(libs.okhttp.signpost) // "se.akerfeldt:okhttp-signpost:1.1.0"
implementation(libs.signpost.core) // "oauth.signpost:signpost-core:2.1.1"
implementation(libs.retrofit)
implementation(libs.retrofit.gson)
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
}

2. Declare the qualifiers

One annotation per API. Hilt resolves qualifiers at compile time, so the annotations never need to be read by reflection at runtime.

di/NetworkModule.kt
@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class BrickApp // unauthenticated
@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class BrickLink // OAuth 1.0
@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class BrickWorks // Bearer token

3. Shared logging interceptor

One HttpLoggingInterceptor is shared across all three clients. It is not qualified because there is no ambiguity — only one HttpLoggingInterceptor exists in the graph.

di/NetworkModule.kt
@Provides
@Singleton
fun providesLoggingInterceptor(): HttpLoggingInterceptor =
HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BODY
} else {
HttpLoggingInterceptor.Level.NONE
}
redactHeader("Authorization")
}

4. Unauthenticated client (BrickApp)

No interceptor beyond logging. Simple, no credentials.

di/NetworkModule.kt
@BrickApp
@Provides
@Singleton
fun providesBrickAppOkHttpClient(
loggingInterceptor: HttpLoggingInterceptor,
): OkHttpClient =
OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.connectTimeout(20, TimeUnit.SECONDS)
.build()

The OAuth credentials are not static — the user pairs their BrickLink account in the settings screen and the consumer key, consumer secret, token, and token secret are written to SettingRepository. The interceptor re-reads them on every request so credential rotation takes effect immediately without restarting the app.

di/NetworkModule.kt
@BrickLink
@Provides
@Singleton
fun providesBrickLinkOkHttpClient(
settingRepository: SettingRepository,
loggingInterceptor: HttpLoggingInterceptor,
): OkHttpClient {
val dynamicSigningInterceptor = Interceptor { chain ->
val consumer = OkHttpOAuthConsumer(
settingRepository.getConsumerKey(),
settingRepository.getConsumerSecret(),
).apply {
setTokenWithSecret(
settingRepository.getToken(),
settingRepository.getTokenSecret(),
)
}
SigningInterceptor(consumer).intercept(chain)
}
return OkHttpClient.Builder()
.addInterceptor(dynamicSigningInterceptor)
.addInterceptor(loggingInterceptor)
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.build()
}

The OkHttpOAuthConsumer is constructed inside the interceptor lambda, not outside it. If you construct it once at module provision time, it captures the credentials at that moment and never picks up changes. The lambda runs on every request, so it always has the current values.

6. Bearer token client (BrickWorks)

The access token is stored in EncryptedSharedPreferences via TokenStore. The interceptor reads it per request for the same reason as the OAuth client.

di/NetworkModule.kt
@BrickWorks
@Provides
@Singleton
fun providesBrickWorksOkHttpClient(
tokenStore: TokenStore,
loggingInterceptor: HttpLoggingInterceptor,
): OkHttpClient {
val authInterceptor = Interceptor { chain ->
val token = tokenStore.getAccessToken()
val request = chain.request().newBuilder()
.apply {
if (token.isNotBlank()) {
addHeader("Authorization", "Bearer $token")
}
}
.build()
chain.proceed(request)
}
return OkHttpClient.Builder()
.addInterceptor(authInterceptor)
.addInterceptor(loggingInterceptor)
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.build()
}

The isNotBlank() guard matters. Sending Authorization: Bearer (empty) to the server causes a 401 that looks identical to an expired token. At least with a blank guard the header is absent and the server’s unauthenticated error path fires instead, which is easier to distinguish in logs.

7. Retrofit instances

Each Retrofit is qualified and receives its matching OkHttpClient via the @BrickApp/@BrickLink/@BrickWorks qualifier on the parameter.

di/NetworkModule.kt
@BrickApp
@Provides
@Singleton
fun providesBrickAppRetrofit(
@BrickApp okHttpClient: OkHttpClient,
gson: Gson,
): Retrofit =
Retrofit.Builder()
.baseUrl(AppUrl.BASE_URL_BRICKOGNIZE)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
@BrickLink
@Provides
@Singleton
fun providesBrickLinkRetrofit(
@BrickLink okHttpClient: OkHttpClient,
gson: Gson,
): Retrofit =
Retrofit.Builder()
.baseUrl(AppUrl.BASE_URL_BRICK_LINK)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
@BrickWorks
@Provides
@Singleton
fun providesBrickWorksRetrofit(
@BrickWorks okHttpClient: OkHttpClient,
gson: Gson,
): Retrofit =
Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()

8. Service creation

Service interfaces are not qualified — there is only one BrickAppService, one BrickLinkApiService, and one BrickWorkService. The qualifier on the Retrofit parameter resolves which instance each service is built from.

di/NetworkModule.kt
@Provides
@Singleton
fun providesBrickAppApiService(@BrickApp retrofit: Retrofit): BrickAppService =
retrofit.create(BrickAppService::class.java)
@Provides
@Singleton
fun providesBrickLinkApiService(@BrickLink retrofit: Retrofit): BrickLinkApiService =
retrofit.create(BrickLinkApiService::class.java)
@Provides
@Singleton
fun providesBrickWorksApiService(@BrickWorks retrofit: Retrofit): BrickWorkService =
retrofit.create(BrickWorkService::class.java)

Testing

The qualifier pattern makes each client independently swappable in tests. Provide a fake SettingRepository that returns hard-coded credentials and verify that requests contain the expected Authorization header:

Terminal window
./gradlew test --tests "*.NetworkModuleTest"
BUILD SUCCESSFUL in 3s
6 tests completed

Use MockWebServer to intercept requests and assert on headers without hitting live APIs.

Pitfalls

Production considerations

All three clients are @Singleton. OkHttpClient holds a thread pool and a connection pool. Providing a new instance per ViewModelComponent scope would create a new pool per ViewModel, which is wasteful and breaks connection reuse. Singleton here is correct.

Token refresh is not handled in these interceptors — the BrickWorks interceptor reads whatever token is currently in TokenStore. A 401 response handler that calls the refresh endpoint and retries the original request belongs in an Authenticator, not an Interceptor. Adding that is the natural next step once the base client structure above is in place.

Wrapping up

You now have three isolated, singleton Retrofit clients with distinct authentication strategies, each injected without ambiguity via Hilt qualifiers. The logging interceptor is shared, credentials are read per-request, and the module compiles without duplicate-binding errors.

The next problem you will hit is token refresh: OkHttpClient.Builder.authenticator() is where that logic belongs, and it needs access to the same TokenStore that the Bearer interceptor uses.

Going deeper

Three clients, one connection pool. Each OkHttpClient.Builder() above creates its own connection pool, dispatcher and thread pool. Build one base client instead and derive the others with newBuilder(). Derived clients share the pool and dispatcher but keep their own interceptors:

di/NetworkModule.kt
@Provides @Singleton
fun baseClient(logging: HttpLoggingInterceptor): OkHttpClient =
OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.callTimeout(60, TimeUnit.SECONDS)
.build()
@BrickWorks @Provides @Singleton
fun brickWorksClient(base: OkHttpClient, auth: BearerInterceptor, logging: HttpLoggingInterceptor) =
base.newBuilder()
.addInterceptor(auth)
.addInterceptor(logging) // last, so it logs the final request
.build()

Interceptor order matters too: application interceptors run in the order they are added, so logging goes last to record the request as it is actually sent.

Token refresh without a stampede. When a token expires, every in-flight request gets a 401 at once. A naive Authenticator then fires several refresh calls in parallel, and with rotating refresh tokens all but one of them fail and log the user out. The fix is single-flight refresh: inside authenticate(), take a lock, check whether the token already changed since this request was sent (another thread refreshed it), and only call the refresh endpoint if it didn’t. Return null after one retry to avoid loops.

Testing each client with MockWebServer. Point the qualified Retrofit at mockWebServer.url("/"), make a call, then assert on mockWebServer.takeRequest(): the BrickWorks request has Authorization: Bearer …, the BrickLink request has an OAuth Authorization: OAuth oauth_consumer_key=… header, and the unauthenticated client sends neither. That one test catches a client wired to the wrong qualifier.