I have this service where I want to put the token as an interception in the okhttp instead of passing as a parameter with @Header("MY_API_KEY")
This is my code regarding the service
/**
* Provides the [PHService]
*/
fun provideService(): PHService {
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BASIC
val client = OkHttpClient.Builder()
.addInterceptor(logger)
.build()
return Retrofit.Builder()
.baseUrl(BuildConfig.API_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(PHService::class.java)
}
How can I add an interceptor for header authorization in here?
Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks.
OkHttp is an interceptor which helps you to log your API calls.
Solution 1: Sharing Default OkHttp Instance In order to make them share a single OkHttp instance, you can simply pass it explicitly on the builder: OkHttpClient okHttpClient = new OkHttpClient(); Retrofit retrofitApiV1 = new Retrofit. Builder() . baseUrl("https://futurestud.io/v1/") .
Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls. Here's a simple interceptor that logs the outgoing request and the incoming response. class LoggingInterceptor implements Interceptor { @Override public Response intercept(Interceptor.
add like this
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", "MY_API_KEY"); // <-- this is the important line
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
httpClient.connectTimeout(30, TimeUnit.SECONDS);
httpClient.readTimeout(30, TimeUnit.SECONDS);
httpClient.addNetworkInterceptor(logging);
OkHttpClient client = httpClient.build();
in kotlin its like
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY
val httpClient = OkHttpClient.Builder()
httpClient.addInterceptor { chain ->
val original = chain.request()
// Request customization: add request headers
val requestBuilder = original.newBuilder()
.header("Authorization", "MY_API_KEY") // <-- this is the important line
val request = requestBuilder.build()
chain.proceed(request)
}
httpClient.connectTimeout(30, TimeUnit.SECONDS)
httpClient.readTimeout(30, TimeUnit.SECONDS)
httpClient.addNetworkInterceptor(logging)
val okHttpClient=httpClient.build()
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