在Okhttp中处理身份验证 [英] Handling Authentication in Okhttp
问题描述
根据OKHttp文档,我将OkHttp 2.3
与基本身份验证请求一起使用,它会自动重试未经身份验证的请求,但是每当我提供无效的凭据时,该请求就会花费太多时间,最终我会收到此异常: >
I'm using OkHttp 2.3
with basic authentication requests, according to OKHttp docs, it automatically retries unauthenticated requests, but whenever I provide invalid credentials, the request takes too much time and I get this exception in the end:
java.net.ProtocolException:后续请求过多:21
java.net.ProtocolException: Too many follow-up requests: 21
如何防止OkHttp自动重试未经身份验证的请求,而是返回401 Unauthorized
?
How can I prevent OkHttp from automatically retrying unauthenticated requests, and return 401 Unauthorized
instead?
推荐答案
protected Authenticator getBasicAuth(final String username, final String password) {
return new Authenticator() {
private int mCounter = 0;
@Override
public Request authenticate(Proxy proxy, Response response) throws IOException {
if (mCounter++ > 0) {
throw new AuthenticationException(
AuthenticationException.Type.INVALID_LOGIN, response.message());
}
String credential = Credentials.basic(username, password);
return response.request().newBuilder().header("Authorization", credential).build();
}
@Override
public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
return null;
}
};
}
在我的身份验证器中,我只计算尝试次数-X尝试之后,我抛出异常.
In my Authenticator I simply count the tries - after X tries, I throw an exception.
这篇关于在Okhttp中处理身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!