Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i change @Query parameter using Interceptor?

Tags:

android

kotlin

I have function:

@GET("weather")
    fun getWeatherByCityName(
        @Query("q") cityName: String,
        @Query("appid") appId: String = API_KEY,
        @Query("units") unit: String,
        @Query("lang") lang: String
    ): Call<WeatherResult>

I want to localize my app so i need to change two fields of this request: units and lang. I want my interceptor to get this request and change it. How can i make my interceptor do this?

val client = OkHttpClient.Builder().apply {
            if (BuildConfig.DEBUG) {
                addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            }
        }.build()
        val json = Json { ignoreUnknownKeys = true }
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(json.asConverterFactory(CONTENT_TYPE.toMediaType()))
            .build()
    }
like image 533
SoulReaver313 Avatar asked Feb 02 '26 19:02

SoulReaver313


1 Answers

I think you can do something like this

class MyInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val oldRequest = chain.request()
        val url = oldRequest.url.newBuilder().apply {

            // Adding old queries to the request
            oldRequest.url.queryParameterNames.forEach { name ->
                if (name == "lang") {
                    addQueryParameter(name,"GET THE LOCALE OR YOUR CUSTOM LOGIC")
                } else {
                    addQueryParameter(name, oldRequest.url.queryParameter(name))
                }
            }

            // Any custom parameters
            addQueryParameter("Your value here", "Here too")
        }.build()
        val newRequest = oldRequest.newBuilder().url(url).build()
        return chain.proceed(newRequest)
    }
}
like image 132
OhhhThatVarun Avatar answered Feb 05 '26 09:02

OhhhThatVarun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!