我正在制作一个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。
关于我遗失或做错的任何想法?
非常感谢!
答案 0 :(得分:0)
使用
添加为NetworkInterceptoraddNetworkInterceptor(NetworkInterceptor)
请参阅此链接以进一步说明:https://github.com/square/okhttp/wiki/Interceptors