1. Introduction

This short tutorial is going to cover how to configure basic authentication on Unirest for Java, a simplified, lightweight HTTP request library built and maintained by Mashape.

2. Configure Basic Authentication on Unirest for Java

2.1. Library dependency

The only one Maven dependency for this example is the unirest-java, version 1.4.9. There are dependencies for Unirest-Java such as Apache Httpclient, Json, we will find them included automatically in the classpath.

The sample source code and related can be found on my Github project.

2.2. Basic Authentication with Native API

Unirest supports Basic Authentication natively. As as result, authenticating the request with basic authentication can be done simply by calling the basicAuth(username, password) function, for example:

2.3. Basic Authentication with Raw HTTP Headers

The “Basic” HTTP authentication scheme is defined inĀ RFC 7617, which transmits credentials as user ID/password pairs, encoded using base64. Therefore, another approach for us to configure basic authentication on Unirest for Java is to construct and send the HTTP headers manually with the request by ourselves. Let’s see the below example:

At first, we need to encode the pair of username and password using Base64, then include the encoded value in the request header.

3. Conclusion

The tutorial has illustrated several ways to configure basic authentication on Unirest for Java. Again, the sample source code presented in the tutorial, you can find on my Github project. It’s is a Maven based project, so it’s easy to run or to be imported in IDE such as Eclipse, IntelliJ, etc.

Below are other related articles for your references:

Java REST Client Example

Set Timeouts with Unirest for Java

Java REST Client Using Unirest Java API

 

0 0 vote
Article Rating