通过OkHttp拦截器拦截重试调用

Intercept and retry call by means of OkHttp Interceptors

我需要在 OkHttp Interceptor 内重试请求。例如,有一个传入请求需要 Authorization 令牌。如果 Authorization 令牌过期,服务器 returns 响应 403 代码。在这种情况下,我正在检索一个新令牌并尝试使用相同的 chain 对象再次进行调用。

但是 OkHttp 抛出一个异常,它表明您不能使用同一个 chain 对象发出两个请求。

java.lang.IllegalStateException: network interceptor org.app.api.modules.ApplicationApiHeaders@559da2 must call proceed() exactly once

我想知道是否有一个干净的解决方案来解决 OkHttp Interceptor 中重试网络请求的问题?

public final class ApplicationApiHeaders implements Interceptor {
    private static final String AUTHORIZATION = "Authorization";
    private TokenProvider mProvider;

    public ApplicationApiHeaders(TokenProvider provider) {
        mProvider = provider;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Token token = mProvider.getApplicationToken();
        String bearerToken = "Bearer " + token.getAccessToken();

        System.out.println("Token: " + bearerToken);
        Request request = chain.request();
        request = request.newBuilder()
                .addHeader(AUTHORIZATION, bearerToken)
                .build();

        Response response = chain.proceed(request);
        if (!response.isSuccessful() && isForbidden(response.code())) {
            Token freshToken = mProvider.invalidateAppTokenAndGetNew();
            String freshBearerToken = freshToken.getAccessToken();

            Request newRequest = chain.request();
            newRequest = newRequest.newBuilder()
                    .addHeader(AUTHORIZATION, freshBearerToken)
                    .build();

            response = chain.proceed(newRequest);
        }

        return response;
    }

    private static boolean isForbidden(int code) {
        return code == HttpURLConnection.HTTP_FORBIDDEN;
    }
}

使用 .interceptors() 而不是 .networkInterceptors() 允许多次调用 .proceed()

有关详细信息,请参阅:https://square.github.io/okhttp/interceptors/