如果我从服务器收到 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/