HTTP Client Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll take a look at basic authentication. We'll see how it works and configure the Java HttpClient to use this kind of authentication.

2. Basic Authentication

Basic authentication is a simple authentication method. Clients can authenticate via username and password. These credentials are sent in the Authorization HTTP header in a specific format. It begins with the Basic keyword, followed by a base64-encoded value of username:password. The colon character is important here. The header should strictly follow this format.

For example, to authenticate with baeldung username and HttpClient password we must send this header:

Basic YmFlbGR1bmc6SHR0cENsaWVudA==

We can verify it by using a base64 decoder and checking the decoded result.

3. Java HttpClient

Java 9 introduced a new HttpClient as an incubated module which was standardized in Java 11. We’ll use Java 11, so we can simply import it from the java.net.http package without any extra configuration or dependencies.

Let’s start by executing a simple GET request without any authentication for now:

HttpClient client = HttpClient.newHttpClient();

HttpRequest request = HttpRequest.newBuilder()
  .GET()
  .uri(new URI("https://postman-echo.com/get"))
  .build();

HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

logger.info("Status {}", response.statusCode());

Firstly, we create an HttpClient, which can be used to execute HTTP requests. Secondly, we create an HttpRequest using the builder design pattern. The GET method sets the HTTP method of the request. The uri method sets the URL where we would like to send the request.

After that, we send the request using our client. The second parameter of the send method is a response body handler. This tells the client that we would like to treat the response body as a String.

Let’s run our application and check the logs. The output should look like this:

INFO com.baeldung.httpclient.basicauthentication.HttpClientBasicAuthentication - Status 200

We see that the HTTP status is 200, meaning our request was successful. After this, let's see how we can handle authentication.

4. Using HttpClient Authenticator

Before we configure authentication we need an URL to test it. Let’s use a Postman Echo endpoint that requires authentication. Firstly, change the previous URL to this and run the application again:

HttpRequest request = HttpRequest.newBuilder()
  .GET()
  .uri(new URI("https://postman-echo.com/basic-auth"))
  .build();

Let's check the logs and look for the status code. This time we received HTTP status 401 “Unauthorized”. This response code means that the endpoint requires authentication but the client didn’t send any credentials.

Let’s change our client so that it sends the required authentication data. We can do this by configuring the HttpClient Builder and our client will use the credentials we set up. This endpoint accepts the username “postman” with the password “password”. Let’s add an authenticator to our client:

HttpClient client = HttpClient.newBuilder()
  .authenticator(new Authenticator() {
      @Override
      protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication("postman", "password".toCharArray());
      }
  })
  .build();

Let’s run the application again. Now the request is successful and we receive HTTP status 200.

5. Authenticate Using HTTP Headers

We can use another approach to access endpoints that require authentication. We learned from previous sections how the Authorization header is constructed, so we can set its value manually. Although this has to be done per request instead of setting it once via an authenticator.

Let’s remove the authenticator and see how we can set the request headers. We need to construct the header value using base64 encoding:

private static final String getBasicAuthenticationHeader(String username, String password) {
    String valueToEncode = username + ":" + password;
    return "Basic " + Base64.getEncoder().encodeToString(valueToEncode.getBytes());
}

Let's set this value for the Authorization header and run the application:

HttpRequest request = HttpRequest.newBuilder()
  .GET()
  .uri(new URI("https://postman-echo.com/basic-auth"))
  .header("Authorization", getBasicAuthenticationHeader("postman", "password"))
  .build();

Our request is successful which means that we constructed and set the header value correctly.

6. Conclusion

In this short tutorial, we saw what is basic authentication and how it works. We used the Java HttpClient with basic authentication by setting an authenticator for it. We used a different approach to authenticate by setting the HTTP header manually.

As always, the source code for these examples is available over on GitHub.

HTTP Client bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
HTTPClient footer
Comments are closed on this article!