I\'m trying to use Retrofit2,
I want to add Token to my Header Like this:
Authorization: Bearer Token
but the <
You will need to add an Interceptor into the OkHttpClient.
Add a class called OAuthInterceptor.
class OAuthInterceptor(private val tokenType: String, private val accessToken: String) : Interceptor {
override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
var request = chain.request()
request = request.newBuilder().header("Authorization", "$tokenType $accessToken").build()
return chain.proceed(request)
}
}
Following that, when you initialise your RetrofitApiService interface, you will need this.
interface RetrofitApiService {
companion object {
private const val BASE_URL = "https://api.coursera.org/api/businesses.v1/"
fun create(accessToken: String): RetrofitApiService {
val client = OkHttpClient.Builder()
.addInterceptor(OAuthInterceptor("Bearer", accessToken))
.build()
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.client(client)
.build()
return retrofit.create(RetrofitApiService::class.java)
}
}
}
Shout out to Java Code Monk, and visit the reference link for more details. https://www.javacodemonk.com/retrofit-oauth2-authentication-okhttp-android-3b702350