I'm struggling with making 2 different interceptors to my retrofit client i have already one interceptor to add my query api_key into the request and im trying to add the
HttpLoggingInterceptor
with the same retrofit instance is there a way to do this ?
this is my code
import com.example.tvapptest.Services.MovieService
import com.example.tvapptest.Services.ShowService
import com.example.tvapptest.Utils.Constants
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitConfig {
private val interceptor : HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
this.level = HttpLoggingInterceptor.Level.BODY
}
private val client : OkHttpClient = OkHttpClient.Builder().apply {
this.addInterceptor(interceptor)
}.build()
private val clientapi : OkHttpClient = OkHttpClient.Builder().apply {
this.addNetworkInterceptor(ApiInterceptor())
}.build()
// use lazy to insure that only one instance of retrofit will be used - no duplication
private val retrofit : Retrofit by lazy {
Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constants.BASE_URL)
// the issue is here how can i add another interceptor to the same client here
//.client(client)
.client(clientapi)
.build()
}
val movieService : MovieService by lazy {
retrofit.create(MovieService::class.java)
}
val showService : ShowService by lazy {
retrofit.create(ShowService::class.java)
}
}
and this is my ApiInterceptor class
package com.example.tvapptest.Network
import com.example.tvapptest.Utils.Constants
import okhttp3.Interceptor
import okhttp3.Response
// this class is used to intercept the request and add the query param api_key
class ApiInterceptor() : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val original = chain.request()
val originalHttpUrl = original.url
val requestBuilder = original.newBuilder().url(originalHttpUrl.newBuilder().addQueryParameter("api_key",Constants.API_KEY).build())
return chain.proceed(requestBuilder.build())
}
}
Is there any reasons for wanting two different clients? Seems like you would be fine with using just one and adding both the interceptors to the same client.
This is something in the lines of what it looks like in kotlin.
OkHttpClient.Builder()
.addInterceptor(interceptor)
.addNetworkInterceptor(ApiInterceptor())
.build()
}