OkHttp令牌拦截器永远重试

时间:2018-04-13 03:47:05

标签: android kotlin retrofit2 rx-java2 okhttp3

我正在制作一个OkHttp拦截器,所以当任何终点返回401错误时它会重试登录,但是拦截器会永远循环。

我也试过添加一个计数器,但计数器每次都会重置。

这是我的代码:

object Service {

    private fun getOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
                .addInterceptor(getLoggingInterceptor())
                .addInterceptor(NetworkInterceptor())
                .build()
    }

    private fun getRetrofit(): Retrofit {
        return Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(getOkHttpClient())
                .baseUrl(getBaseUrl())
                .build()
    }
}

class NetworkInterceptor: Interceptor {
    var counter = 0

    override fun intercept(chain: Interceptor.Chain): Response? {
        val originalResponse = chain.proceed(chain.request())

        if (!originalResponse.isSuccessful && originalResponse.code() == 401) {
            Log.e("NetworkInterceptor", "Network error 401. Counter = $counter")
            counter++

            val refreshedToken = refreshToken()
            Log.e("NetworkInterceptor", "refreshedToken = $refreshedToken")
        }


        return originalResponse
    }

    private fun refreshToken(): String {
        val context = MyApp.appContext
        val preferencesUtil = SharePreferencesUtils(context)
        val username = preferencesUtil.getUsername()
        val password = preferencesUtil.getPassword()
        val login = AuthService().loginSync(username, password).execute()
        return login.body()?.access_token!!
    }
}

我尝试使用Auth调用RxJava Single和常规同步Call<>

在每种情况下,呼叫都会永远发生,401会永远返回,而计数器始终保持为0。

关于我遗失或做错的任何想法?

非常感谢!

1 个答案:

答案 0 :(得分:0)

使用

添加为NetworkInterceptor
addNetworkInterceptor(NetworkInterceptor)

请参阅此链接以进一步说明:https://github.com/square/okhttp/wiki/Interceptors