Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Authentication in Okhttp

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: Too many follow-up requests: 21

How can I prevent OkHttp from automatically retrying unauthenticated requests, and return 401 Unauthorized instead?

like image 747
Silvia H Avatar asked Apr 05 '15 10:04

Silvia H


1 Answers

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;
        }
    };
}

In my Authenticator I simply count the tries - after X tries, I throw an exception.

like image 68
Matthias Bruns Avatar answered Nov 07 '22 01:11

Matthias Bruns