Чтобы сделать заголовок динамическим, я использую Header-interceptor при использовании Retrofit,
class HeaderInterceptor: Interceptor {
/**
* Interceptor class for setting of the dynamic headers for every request
*/
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
request = request?.newBuilder()
// dynamic token you get should be use instead of #YOUR_DYNAMIC_TOKEN.
?.addHeader("Authorization: Bearer", #YOUR_DYNAMIC_TOKEN)
?.build()
return chain.proceed(request)
}
}
Теперь мы можем использовать его, как показано ниже
@Provides
@Singleton
fun getOkHttpClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val builder = OkHttpClient.Builder()
builder.addInterceptor(interceptor)
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.addInterceptor(HeaderInterceptor())
return builder.build()
}
или просто мы можем использовать его как:
@Provides
@Singleton
fun getOkHttpClient(): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
val builder = OkHttpClient.Builder()
builder.addInterceptor(interceptor)
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.followRedirects(true)
.followSslRedirects(true)
.addInterceptor { chain ->
val newRequest = chain.request().newBuilder()
.addHeader("Authorization: Bearer", #YOUR_DYNAMIC_TOKEN)
.build()
chain.proceed(newRequest)
}
}