Sobes.tech
Middle+

Retrofit kitabxanasında bütün sorğuları necə dəyişdirmək olar?

sobes.tech Süni İntellekt

AI-dan cavab

Interceptor. Retrofit tərəfindən istifadə olunan OkHttpClient-ə əlavə olunur. Interceptor, göndərilmədən əvvəl sorğunu və işlənmədən əvvəl cavabı dəyişə bilər.

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

Öz Interceptor tətbiqinizi yaradın və onu OkHttpClient.Builder-a əlavə edin:

class MyChangingInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()
        val newRequest = originalRequest.newBuilder()
            // Nümunə: başlıq əlavə et
            .addHeader("X-Custom-Header", "SomeValue")
            // Nümunə: URL dəyişdir
            // .url("https://new.api.com" + originalRequest.url.encodedPath)
            // Nümunə: metod dəyişdir (əgər lazım olsa)
            // .method("POST", originalRequest.body)
            .build()
        return chain.proceed(newRequest)
    }
}

Interceptor-u OkHttpClient-a əlavə edin:

val client = OkHttpClient.Builder()
    .addInterceptor(MyChangingInterceptor())
    // Bir neçə interceptor əlavə edə bilərsiniz
    // .addInterceptor(AnotherInterceptor())
    .build()

Yaradılmış OkHttpClient-i istifadə edərək Retrofit nümunəsini yaradın:

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