登录后会得到一条token,保存在本地,每次访问接口就在header携带上token
在拦截器中这样做
var token = "这里是登陆后返回的token,保存在sharepreference文件"
class TokenFreshInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
// synchronized(this) {
// synchronized(this) 是同步代码锁,使请求同步而非异步,现在注释,因为token过期并发已经处理了
/**
* 添加头部token
*/
val originalRequest = chain.request()
val request = chain.request().newBuilder()
.header("Authorization", "Bearer $token")
.header("Accept", "application/vnd.openfood.v1+json")
.method(originalRequest.method(), originalRequest.body())
val response = chain.proceed(request.build())
/**
* 因为接口api/rider/location 一定要token,但是可能在token过期状态下会重复调用,所以需要将这个接口的过期处理过滤出来
*/
if (response.code() == 401 && !originalRequest.url().toString().contains("api/rider/location")) {
//过期,去登陆
Preference.clearPreference(UriConstant.TOKEN)
Preference.clearPreference(UriConstant.USERINFO)
val intent = Intent(DeliveryApplication.context, LoginActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
DeliveryApplication.context.startActivity(intent)
}
val headers = response.headers()
var newToken = headers["Authorization"]
//如果接口返回新的token,需要捕获下来并且替换旧的token保存本地
if (newToken != null && newToken.isNotEmpty()) {
if (newToken.startsWith("Bearer")) {
newToken = newToken.split(" ")[1]
}
token = newToken
val newRequest = chain.request().newBuilder()
.header("Authorization", "Bearer $token")
.header("Accept", "application/vnd.openfood.v1+json")
.method(originalRequest.method(), originalRequest.body())
.build()
return chain.proceed(newRequest)
}
return response
// }
}
}