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()
}
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With