Retrofit insert same query parameters for ALL endpoints

Viewed 285

I have token parameters to insert in ALL Retrofit services. Currently all each requests, I insert a @QueryMap

    @GET("resources/{resourceId}")
    suspend fun request(
        @Path("resourceId") resId: Int,
        @QueryMap tokens: Map<String, String>
    ): Response

so that https://baseurl.com/resources?key1=value1&key2=value2

The Map values are constant () ex: key1=value1&key2=value2

Now I have multiple endpoints (and multiple services), how to insert the query parameters in all endpoints ? (without passing in the method).

It seems OkHttp can insert with interceptors.

1 Answers

Thanks to link by @rahat

So you can inject via OkHttpClient by following this code snippet

import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

fun provideOkHttpClient(): OkHttpClient {
    val httpClient = OkHttpClient.Builder()

    httpClient.addInterceptor(object : Interceptor {
        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val original: Request = chain.request()
            val originalHttpUrl: HttpUrl = original.url
            // INTERESTING PART to inject query parameters
            val url = originalHttpUrl.newBuilder()
                .addQueryParameter("query_key1", "query_value1")
                .addQueryParameter("query_key2", "query_value2")
                .build()
            // INTERESTING PART to inject query parameters

            // Request customization: add request headers
            val requestBuilder: Request.Builder = original.newBuilder()
                .url(url)
            val request: Request = requestBuilder.build()
            return chain.proceed(request)
        }
    })

    return httpClient.build()
}


Then your wire up with dependency injection Retrofit and the Service

// provide your OkHttpClient
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
    return Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttpClient)
        .build()
}

fun provideTrackService(retrofit: Retrofit): YourService {
    return retrofit.create(YourService::class.java)
}
Related