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

2022-09-01 01:02:42

我需要在 .例如,有需要令牌的传入请求。如果令牌已过期,服务器将返回带有代码的响应。在本例中,我正在检索新令牌并尝试使用相同的对象再次进行调用。OkHttp InterceptorAuthorizationAuthorization403chain

但是 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;
    }
}

答案 1

使用允许多次调用的代替。.interceptors().networkInterceptors().proceed()

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


答案 2

推荐