Sobes.tech
Middle+

Retrofit kutubxonasidagi barcha so'rovlarni qanday o'zgartirish mumkin?

sobes.tech AI

AIdan javob

Interceptor. Retrofit tomonidan ishlatiladigan OkHttpClient ga qo'shiladi. Interceptor so'rovni yuborishdan oldin va javobni ishlashdan oldin o'zgartirishi mumkin.

interface Interceptor {
    fun intercept(chain: Interceptor.Chain): Response
}

O'z Interceptor implementatsiyangizni yarating va uni OkHttpClient.Builder ga qo'shing:

class MyChangingInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val newRequest = originalRequest.newBuilder()
            // Misol uchun: sarlavha qo'shish
            .addHeader("X-Custom-Header", "SomeValue")
            // Misol uchun: URL ni o'zgartirish
            // .url("https://new.api.com" + originalRequest.url.encodedPath)
            // Misol uchun: metodni o'zgartirish (agar kerak bo'lsa)
            // .method("POST", originalRequest.body)
            .build()
        return chain.proceed(newRequest)
    }
}

Interseptorni OkHttpClient ga qo'shing:

val client = OkHttpClient.Builder()
    .addInterceptor(MyChangingInterceptor())
    // Bir nechta interseptorlar qo'shishingiz mumkin
    // .addInterceptor(AnotherInterceptor())
    .build()

Yaratilgan OkHttpClient bilan Retrofit instansiyasini yarating:

val retrofit = Retrofit.Builder()
    .baseUrl("https://your.api.com/")
    .client(client)
    .addConverterFactory(GsonConverterFactory.create())
    .build()