改用新令牌请求重试?

时间:2020-10-21 12:27:03

标签: java kotlin retrofit retrofit2

当任何请求返回TOKEN_IS_NOT_ACTIVE时,我将获得一个新令牌,然后我将获得一个新令牌

在拦截器中

override fun intercept(chain: Interceptor.Chain): Response {
    val request = chain.request()
    var response = chain.proceed(request)
    val bodyString = response.peekBody(AppConstants.BUFFER_SIZE_2MB)?.string()

    val json = JSONObject(bodyString)
//after get new token retry with the failedRequest
    if(json.has("token"){
         failedRequest=failedRequest.newBuilder().removeHeader("Authorization").removeHeader("")
                                    .addHeader("Authorization", "bearer " +json.getString("access_token"))
                                    .addHeader("source_id", Math.random().toString()

                                    ).build()

                            isNewTokenAfterFaild=false
                            return chain.proenter code hereceed(failedRequest)
}


if (resultObj.code == AppConstants.TOKEN_IS_NOT_ACTIVE )
{

  failedRequest=chain.request()
  getTokenOnce() -> make retrofit HTTP request
}

     return response // this line make a problem for me because this will proceed the chain,
                     //and callback will be notified with the failed request 



}

有什么办法可以阻止代码返回新令牌,并解决这个问题

令牌代码

fun getToken(context: Context) = CoroutineScope(Dispatchers.IO).async {

         val requestMap = prepareTokenHeader(context)
        val tokenEndpoint = RetrofitClientInstance.buildService(TokenService::class.java)

            val token = tokenEndpoint.getToken(
                    AppConstants().tokenBaseUrl,
                    requestMap
            )

0 个答案:

没有答案