改造为所有端点插入相同的查询参数

Retrofit insert same query parameters for ALL endpoints

我有令牌参数要插入到所有 Retrofit 服务中。 目前所有的每个请求,我插入一个 @QueryMap

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

所以https://baseurl.com/resources?key1=value1&key2=value2

Map 值是常量 () 例如:key1=value1&key2=value2

现在我有多个端点(和多个服务),如何在所有端点插入查询参数?(不传入方法)。

OkHttp 好像可以用拦截器插入。

感谢@rahat

的link

因此您可以按照以下代码片段

通过OkHttpClient注入
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()
}


然后连接依赖注入 Retrofit 和服务

// 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)
}