Mike6679 Mike6679 - 2 days ago 6
Java Question

"OkHttpClient cannot be converted to MyOkHttpClient"

Why wont this compile:

MyOkHttpClient okClient = new MyOkHttpClient.Builder()
.addInterceptor(new AddCookiesInterceptor())
.addInterceptor(new ReceivedCookiesInterceptor()).build();


Incompatible types.
Required:
my.path.util.auth.MyOkHttpClient
Found:
okhttp3.OkHttpClient

This is MY class:

public class MyOkHttpClient extends okhttp3.OkHttpClient implements Authenticator {

private static int MAX_AUTHENTICATE_TRIES = 3;



@Override
public Request authenticate(Route route, Response response) throws IOException {
if (responseCount(response) >= MAX_AUTHENTICATE_TRIES) {
return null; // If we've failed 3 times, give up. - in real life, never give up!!
}
String credential = Credentials.basic(AUTHTOKEN_USERNAME, AUTHTOKEN_PASSWORD);
return response.request().newBuilder().header("Authorization", credential).build();
}

private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}


}

Answer

Based on your comments, you incorrectly believe that you are decorating OkHttpClient with custom authentication logic.

Instead, you are unnecessarily extending OkHttpClient and implementing the Authenticator interface. You can simply build the standard OkHttpClient with any custom authenticator you would like.

As such, this is more like what you actually want

public class MyAuthenticator implements Authenticator {

    private static int MAX_AUTHENTICATE_TRIES = 3;

    @Override
    public Request authenticate(Route route, Response response) throws IOException {
        if (responseCount(response) >= MAX_AUTHENTICATE_TRIES) {
            return null; // If we've failed 3 times, give up. - in real life, never give up!!
        }
        String credential = Credentials.basic(AUTHTOKEN_USERNAME, AUTHTOKEN_PASSWORD);
        return response.request().newBuilder().header("Authorization", credential).build();
    }

    private int responseCount(Response response) {
        int result = 1;
        while ((response = response.priorResponse()) != null) {
            result++;
        }
        return result;
    }


}

And then when you build your client

OkHttpClient okClient = new OkHttpClient.Builder()
            .addInterceptor(new AddCookiesInterceptor())
            .addInterceptor(new ReceivedCookiesInterceptor())
            .authenticator(new MyAuthenticator())
            .build();
Comments