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

Note that we have used use the Credentials.basic(username, password) method to encode the request header.

2.2. Use the client to access a page that supports basic authentication

2.3. Put it all together

We can provide the URL we want to access and the username, password for authentication with that site.

2.4. Verify

Let’s create a simple unit test to verify the fetch method:

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:

And then we modify the method a little bit as below:

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:

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:

OkHttp Post Examples

Java REST Client Examples Using OkHttp

Download a File with OkHttp

Upload a File with OkHttp

Set Timeout with OkHttp

How to Cache Response with OkHttp

0 0 vote
Article Rating