OkHttp provides support for user authentication. When the status code of the HTTP response is 401, OkHttp will get the new Request object from the set Authenticator object and try to issue the request again. The authenticate method in the Authenticator interface is used to provide a Request object for authentication, and the authenticateProxy method is used to provide a Request object for authentication for a proxy server.
Example of user authentication:
OkHttpClient client = new OkHttpClient(); (new Authenticator() { public Request authenticate(Proxy proxy, Response response) throws IOException { String credential = ("user", "password"); return ().newBuilder() .header("Authorization", credential) .build(); } public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } });
Advanced
When you need to implement a Basic challenge, use (username, password) to encode the request header.
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { (new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) { ("Authenticating for response: " + response); ("Challenges: " + ()); String credential = ("jesse", "password1"); return ().newBuilder() .header("Authorization", credential) .build(); } @Override public Request authenticateProxy(Proxy proxy, Response response) { return null; // Null indicates no attempt to authenticate. } }); Request request = new () .url("/secrets/") .build(); Response response = (request).execute(); if (!()) throw new IOException("Unexpected code " + response); (().string()); }