在Okhttp中处理身份验证 [英] Handling Authentication in Okhttp

查看:188
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆