我有一个应用程序,需要会话(cookie)来处理网络电话.我正在使用Retrofit Rx
Java.但是,会话可能会过期(使用401 Unauthorized状态进行Retrofit错误)并且我想重新进行身份验证(以获取新的cookie)并在此情况下重试之前的呼叫.我如何用RxJava做到这一点?
我的例子:
getServerApi().getDialogs(offset,getCookies()) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .retryWhen(observable -> {...}) // Need some logic .subscribe(dialogsEnvelope -> getView().setDialogs(dialogsEnvelope),throwable -> getView().setError(processFail(throwable)));
解决方法
使用OkHttp非常强大的
Interceptor
.
public class RecoverInterceptor implements Interceptor { String getAuth() { // check if we have auth,if not,authorize return "Bearer ..."; } void clearAuth() { // clear everything } @Override public Response intercept(Chain chain) throws IOException { final Request request = chain.request(); if (request.urlString().startsWith("MY ENDPOINT")) { final Request signed = request.newBuilder() .header("Authorization",getAuth()) .build(); final Response response = chain.proceed(signed); if (response.code() == 401) { clearAuth(); return intercept(chain); } else { return response; } } else { return chain.proceed(request); } } }