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
1 2 3 4 5 |
<dependency> <groupId>com.mashape.unirest</groupId> <artifactId>unirest-java</artifactId> <version>1.4.9</version> </dependency> |
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:
1 2 3 4 5 6 7 8 9 |
@Test public void testBasicAuthAPI() throws IOException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/basic-auth/user/passwd") .basicAuth("user", "passwd") .asJson(); assertThat(response.getStatus(), equalTo(200)); } |
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:
1 2 3 4 5 6 7 8 9 |
@Test public void testBasicAuthRawHeader() throws IOException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/basic-auth/user/passwd"). header("Authorization", "Basic " + Base64Coder.encodeString("user" + ":" + "passwd")) .asJson(); assertThat(response.getStatus(), equalTo(200)); } |
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:
Set Timeouts with Unirest for Java
Java REST Client Using Unirest Java API