In this tutorial, we’re going to show you an example about how to do Basic Authentication with OkHttp, an HTTP & HTTP/2 client for Android and Java applications, powered by Square.
1. Overview
OkHttp can automatically retry unauthenticated requests forever. So, if a response is 401 Not Authorized, we should build a new request and include a credential. If there is no credential available, we should return null to skip the retry.
2. Basic Authentication with OkHttp example
In this section, we’re going to use OkHttp to build a client that will access the httpbin, a HTTP Request & Response Service allow us to test basic authentication. Here are the steps in detail:
2.1. Create an OkHttpClient client object and supply it with a credential
1 2 3 4 5 6 7 8 9 10 11 |
private static OkHttpClient createAuthenticatedClient(final String username, final String password) { // build client with authentication information. OkHttpClient httpClient = new OkHttpClient.Builder().authenticator(new Authenticator() { public Request authenticate(Route route, Response response) throws IOException { String credential = Credentials.basic(username, password); return response.request().newBuilder().header("Authorization", credential).build(); } }).build(); return httpClient; } |
2.2. Use the client to access a page that supports basic authentication
1 2 3 4 5 6 7 8 9 |
private static Response doRequest(OkHttpClient httpClient, String anyURL) throws Exception { Request request = new Request.Builder().url(anyURL).build(); Response response = httpClient.newCall(request).execute(); if (!response.isSuccessful()) { throw new IOException("Unexpected code " + response); } System.out.println(response.body().string()); return response; } |
2.3. Put it all together
We can provide the URL we want to access and the username, password for authentication with that site.
1 2 3 4 5 6 7 |
public static Response fetch(String url, String username, String password) throws Exception { OkHttpClient httpClient = createAuthenticatedClient(username, password); // execute request return doRequest(httpClient, url); } |
2.4. Verify
Let’s create a simple unit test to verify the fetch method:
1 2 3 4 5 |
@Test public void testFetchOK() throws Exception { String url = "http://httpbin.org/basic-auth/user/passwd"; WebUtils.fetch(url, "user", "passwd"); } |
Note that the “user”, “passwd” are username and password to authenticate the above URL.
3. Improvement
The above example works fine if we supply correct username and password. If we provide incorrect one, the OkHttp client will automatically retry forever. We need several improvement in order to skip the retry somehow.
So, let’s implement a method to count the number of failed responses:
1 2 3 4 5 6 7 |
private static int responseCount(Response response) { int result = 1; while ((response = response.priorResponse()) != null) { result++; } return result; } |
And then we modify the method a little bit as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private static OkHttpClient createAuthenticatedClient(final String username, final String password) { // build client with authentication information. OkHttpClient httpClient = new OkHttpClient.Builder().authenticator(new Authenticator() { public Request authenticate(Route route, Response response) throws IOException { String credential = Credentials.basic(username, password); if (responseCount(response) >= 3) { return null; } return response.request().newBuilder().header("Authorization", credential).build(); } }).build(); return httpClient; } |
We have just included the code to check the response. If we’ve failed 3 times, then we will give up.
Let’s create unit test to verify the fetch method again:
1 2 3 4 5 |
@Test public void testFetchFailed() throws Exception { String url = "http://httpbin.org/basic-auth/user/passwd"; WebUtils.fetch(url, "user", "passwd1"); } |
The test will be failed.
4. Conclusion
This article shows us a way to configure and user Basic Authentication with OkHttp. The example code can be download by this link: okhttp-basic-auth
This is an Maven based project, so it should be imported into any IDE and run it and here is another related article for your references:
Java REST Client Examples Using OkHttp
How to Cache Response with OkHttp