Middle+
Kuidas muuta kõiki Retrofit teeki päringuid?
sobes.tech AI
Vastus AI-lt
Interceptor. Added to the OkHttpClient used by Retrofit. The interceptor can modify the request before sending and the response before processing.
interface Interceptor {
fun intercept(chain: Interceptor.Chain): Response
}
Create your own implementation of Interceptor and add it to OkHttpClient.Builder:
class MyChangingInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val newRequest = originalRequest.newBuilder()
// Example: add a header
.addHeader("X-Custom-Header", "SomeValue")
// Example: change URL
// .url("https://new.api.com" + originalRequest.url.encodedPath)
// Example: change method (if needed)
// .method("POST", originalRequest.body)
.build()
return chain.proceed(newRequest)
}
}
Add the interceptor to OkHttpClient:
val client = OkHttpClient.Builder()
.addInterceptor(MyChangingInterceptor())
// You can add multiple interceptors
// .addInterceptor(AnotherInterceptor())
.build()
Use the created OkHttpClient when creating the Retrofit instance:
val retrofit = Retrofit.Builder()
.baseUrl("https://your.api.com/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()