android - 在 Volley 中重新登录并重试请求

标签 android android-volley

如果我从服务器收到 401 错误,我需要执行自动重新登录和重试请求(如果成功)。我正在使用 Volley 库。据我从 Volley 源代码中看到的,它在 while (true) 循环中运行,直到它得到响应或异常:

@Override
public NetworkResponse performRequest(Request<?> request){
    while (true) {
        try {
            httpResponse = mHttpStack.performRequest(request, headers);
            return httpResponse;
        } catch (IOException e) {
            statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
                attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
            }
        }
    }
}

但我想停止此循环,直到获得成功的登录响应,然后继续尝试获得响应。

有没有办法在不修改 Volley 源的情况下在自定义 RetryPolicy 中做到这一点?

最佳答案

实现自己的 RetryPolicy 并覆盖 public void retry(VolleyError error) 方法,如下所示:

    @Override
    public void retry(VolleyError error) throws VolleyError {
        if (error.networkResponse.statusCode == HttpStatus.SC_UNAUTHORIZED)
        {
            throw new VolleyError("Client is not authorized, retry is pointless");
        }
    }

关于android - 在 Volley 中重新登录并重试请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23251202/

相关文章:

android - Facebook Android sdk 在身份验证时抛出丢失的重定向 uri

android - Top_toBottomof 在 constraintlayout 中不起作用。如何在Constraint布局中使用Top_toBottomof?

android - 为什么我在聊天应用程序中超时?

android - 无法在Android Volley中将 header 与发布请求附加

java.lang.NoSuchMethodError : No virtual method setTag(Ljava/lang/Object;)

android - 带 Volley 的 SSL 固定

android - 半隐藏 View 的 TranslateAnimation

java - Gradle编译android.jar错误->建议升级编译器

android 我怎样才能在 volley 库中处理 setRequestProperty

android - OkHttp - Android 从 MySQL 数据库获取数据