Funtriaco Prado
Funtriaco Prado

Reputation: 339

Adding custom headers to every request in Kotlin okHttp retrofit2 using the current code

Im trying to add custom headers to every request by adding .addHeader() to the OkHttpClient.Builder() but im getting the following error when building:

MicroApiClient.kt: (16, 14): Unresolved reference: addHeader

How can I correctly add custom headers to every request using the code below?

    package com.app.name.data
    
    import com.app.name.BuildConfig
    import com.app.name.data.source.remote.APPService
    import okhttp3.OkHttpClient
    import okhttp3.logging.HttpLoggingInterceptor
    import retrofit2.Retrofit
    import retrofit2.converter.gson.GsonConverterFactory
    import retrofit2.converter.scalars.ScalarsConverterFactory
    
    object MicroApiClient {
        private val loggingInterceptor = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)
        private val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                // Attempting to add headers to every request
                .addHeader("x-api-key", BuildConfig.AWS_MICROSERVICES_API_KEY)
                .build()
        val instance: APPService by lazy {
            val retrofit = Retrofit.Builder()
                    .baseUrl(BuildConfig.AWS_MICROSERVICES_HOST)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .client(okHttpClient)
                    .build()
    
            retrofit.create(APPService::class.java)
        }
    }

Upvotes: 3

Views: 2726

Answers (2)

Ali Rasouli
Ali Rasouli

Reputation: 1911

It is simple; only use addHeader method. For Example:

var request= Request.Builder()
                .addHeader("Token","test")
                .addHeader("UserName","test user")
                .url(url)
                .post(jsonBody)
                .build()

Upvotes: 0

tahsinRupam
tahsinRupam

Reputation: 6405

As per Retrofit documentation :

Interceptors can add, remove, or replace request headers.

Interceptor are used to manipulate outgoing request or the incoming response. In your case you have to add API_KEY to every request as header. That's where the interceptor can be handy. You can add header in the interceptor as below:

 private val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                // Attempting to add headers to every request
                .addInterceptor { chain ->
                     val request = chain.request().newBuilder()
                     .addHeader("x-api-key", BuildConfig.AWS_MICROSERVICES_API_KEY)
                     chain.proceed(request.build())
                }
                .build()

Upvotes: 4

Related Questions