登錄後會得到一條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
// }
}
}