从OkHttp拦截器内部进行同步Retrofit调用

the*_*ang 5 android interceptor retrofit okhttp

我试图自动刷新auth token它是否已过期.我正在使用Interceptor引入的新类OkHttp 2.2.在intercept方法中,我正在尝试原始请求chain.proceed(request),检查响应代码,如果令牌过期,我正在同步调用单独的Retrofit服务以获取新令牌.

奇怪的是,没有代码通过同步调用似乎运行.如果我尝试在同步调用的行上使用断点进行调试,然后执行一个步骤,我将在Dispatcher.java中停止:

if (!executedCalls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
Run Code Online (Sandbox Code Playgroud)

知道我在这里做错了什么吗?我可能只是手工制作一个新的请求,但我只是好奇为什么一个Retrofit call似乎在这里不起作用.

我的拦截器:

public class ReAuthInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        // try the request
        Response response = chain.proceed(request);

        // if we receive a "401 - Not Authorized" then refresh the auth token and try again
        if (response.code() == 401) {
            // get a new auth token and store it
            UserToken userToken = MobileClient.getOkraService().login(AuthUtil.getUserToken(MSWorksApplication.getContext()));
            AuthUtil.authenticate(MSWorksApplication.getContext(), userToken);

            Log.d("TEST", "TEST TEST TEST");

            // use the original request with the new auth token
            Request newRequest = request.newBuilder().header("Authorization", AuthUtil.getAuthToken(MSWorksApplication.getContext())).build();

            return chain.proceed(newRequest);
        }
        else {
            // the auth token is still good
            return response;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 1

我遇到了这个问题 - 如果您收到的 HTTP 响应代码会导致 Retrofit 调用 failure() 而不是 success(),则会抛出异常。

如果你包裹

UserToken userToken = MobileClient.getOkraService().login(AuthUtil.getUserToken(MSWorksApplication.getContext()));
Run Code Online (Sandbox Code Playgroud)

在 try/catch(RetrofitError e) 中,您将能够在失败后执行代码,但是我发现这非常麻烦,并且仍在寻找更好的解决方案。