retrofit retry with the new token request?

雨燕双飞 提交于 2021-01-29 10:53:24

问题


I get new token when any request return TOKEN_IS_NOT_ACTIVE then I get a new token

In interceptor

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 



}

Is there any way to block the code util new token is returned, and make around with this

token code

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
            )

来源:https://stackoverflow.com/questions/64463506/retrofit-retry-with-the-new-token-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!