这是我要处理的情况,
- 如果请求被执行,并且响应指示授权 token 已过期,
- 发送刷新 token 请求
- 如果刷新 token 请求成功,则重试原始请求
这对调用的Activity、Fragment...等应该是透明的。从调用者的角度来看,这是一个请求,一个响应。
之前直接用OkHttpClient实现过这个流程,不知道Retrofit怎么实现。
也许与这个开放相关的东西 issue关于 ResponseInterceptor?
如果在改造中没有直接的方法来实现这一点,那么最好的实现方法是什么?基础监听器类?
我也在使用带有 Retrofit 的 RoboSpice,如果它在这种情况下有帮助的话。
最佳答案
因为我使用的是 RoboSpice,所以我最终通过创建一个抽象的 BaseRequestListener
来做到这一点。
public abstract class BaseRequestListener<T> implements RequestListener<T> {
@Override
public void onRequestFailure(SpiceException spiceException) {
if (spiceException.getCause() instanceof RetrofitError) {
RetrofitError error = (RetrofitError) spiceException.getCause();
if (!error.isNetworkError()
&& (error.getResponse().getStatus() == INVALID_ACCESS_TOKEN_STATUS_CODE)) {
//I'm using EventBus to broadcast this event,
//this eliminates need for a Context
EventBus.getDefault().post(new Events.OnTokenExpiredEvent());
//You may wish to forward this error to your listeners as well,
//but I don't need that, so I'm returning here.
return;
}
}
onRequestError(spiceException);
}
public abstract void onRequestError(SpiceException spiceException);
}
关于android - 通过在改造中透明地发送另一个请求来处理特定错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22014958/