在 Okhttp 中处理身份验证

Handling Authentication in Okhttp

根据 OKHttp 文档,我将 OkHttp 2.3 用于基本身份验证请求,它会自动重试未经身份验证的请求,但每当我提供无效凭据时,请求都会花费太多时间,并且我在结束:

java.net.ProtocolException: Too many follow-up requests: 21

如何防止 OkHttp 自动重试未经身份验证的请求,而 return 401 Unauthorized 而不是?

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 次尝试后,我抛出异常。

有效的 Traxdata 答案的修改版本:

protected Authenticator getBasicAuth(final String username, final String password) {
    return new Authenticator() {
        private int mCounter = 0;

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            Log.d("OkHttp", "authenticate(Route route, Response response) | mCounter = " + mCounter);
            if (mCounter++ > 0) {
                Log.d("OkHttp", "authenticate(Route route, Response response) | I'll return null");
                return null;
            } else {
                Log.d("OkHttp", "authenticate(Route route, Response response) | This is first time, I'll try to authenticate");
                String credential = Credentials.basic(username, password);
                return response.request().newBuilder().header("Authorization", credential).build();
            }
        }
    };
}

然后你需要:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.authenticator(getBasicAuth("username", "pass"));
retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(builder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

就是这样。