英文:
Add header interceptor after login - Retrofit
问题
我在过去的一些日子里遇到了一个问题,我知道如何设置一个头部拦截器,问题是,我如何在登录后设置一个头部拦截器,因为我的流程是:
首先进行不带身份验证的登录,只使用用户名和密码。
然后服务器返回Bearer令牌。
我该如何自动设置头部验证,而不是在每次调用Retrofit时手动添加它?有没有办法实现这个?
我需要使用相同的Retrofit实例吗?
英文:
I'm having an issue from some days, I know how to set a header interceptor, the thing is, how do I set a header interceptor only after the login because my flow is :
Login without auth just user and password
Then server returns the Bearer token
How do I set the header authentication automatically instead of adding it manually on each call of retrofit? Is there any way?
Do I have to use the same instance of Retrofit?
答案1
得分: 1
你可以通过创建自定义的拦截器来实现,以下是代码示例:
class AuthorizationInterceptor(var context: Context) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request: Request = chain.request()
val sessionId = "Your Session Id"
if (tempSessionId != null) {
request = request.newBuilder()
.addHeader("Authorization", "Bearer $tempSessionId").build()
}
return chain.proceed(request)
}
}
然后按照以下方式添加这个拦截器:
class RetrofitInstance(var context: Context) {
private val BASE_URL = APIVersionConstants.BASE_URL
private val builder = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(makeOkHttpClient())
private fun makeOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(AuthorizationInterceptor(context)) // <----HERE
.build()
}
private val retrofit = builder.build()
fun <T> buildService(serviceType: Class<T>): T {
return retrofit.create(serviceType)
}
}
完成了。
英文:
You can do it by making your custom interceptor, below is the code
class AuthorizationInterceptor(var context: Context) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request: Request = chain.request()
val sessionId = "Your Session Id"
if (tempSessionId != null) {
request = request.newBuilder()
.addHeader("Authorization", "Bearer $tempSessionId").build()
}
return chain.proceed(request)
}
}
And then add this Interceptor by following way
class RetrofitInstance(var context: Context) {
private val BASE_URL = APIVersionConstants.BASE_URL
private val builder = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(makeOkHttpClient())
private fun makeOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(AuthorizationInterceptor(context)) //<----HERE
.build()
}
private val retrofit = builder.build()
fun <T> buildService(serviceType: Class<T>): T {
return retrofit.create(serviceType)
}
}
It's done
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论