Java 11 HttpClient with Basic Authentication

Upasana | December 01, 2019 | 1 min read | 945 views | java-httpclient


In this article, we will create Java 11 HttpClient that accesses Basic Auth protected REST API resource using sync and async mode. We will use Kotlin for reference implementation.

Spring Boot 2 based Basic Auth Server

Follow this article to setup Spring Boot 2 based Basic Auth Server

Else, you can directly download the Basic Auth Server from Github Repository and run it locally using the below command.

Starting the server using Gradle
$ ./gradlew bootRun

Server will expose http://localhost:8080/api/health endpoint, which can be tested using the below curl command.

$ curl -i --user admin:password -X GET http://localhost:8080/api/health

Java 11 HttpClient

Java 11 HttpClient supports Basic Authentication using authenticator.

We can use either send or sendAsync api for making synchronous and asynchronous (fully non-blocking) requests.

HttpClient basic authentication - sync client
fun basicAuthSync() {
    val httpClient: HttpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .authenticator(object : Authenticator() {   (1)
                override fun getPasswordAuthentication(): PasswordAuthentication {
                    return PasswordAuthentication("admin", "password".toCharArray())
                }
            })
            .version(HttpClient.Version.HTTP_1_1)
            .build()

    val request = HttpRequest.newBuilder()
            .GET()
            .uri(URI.create("http://localhost:8080/api/health"))
            .build()

    val httpResponse = httpClient.send(request, BodyHandlers.ofString())
    println("httpResponse statusCode = ${httpResponse.statusCode()}")
    println(httpResponse.body())
}
1 PasswordAuthentication is configured for handling HTTP Basic Authentication.
HttpClient - async client
httpClient.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse<String>::body)
        .thenAccept(System.out::println)
        .join()
Server Response
httpResponse statusCode = 200
{"status":"UP"}

That’s all.


Top articles in this category:
  1. HTTP GET request with Java 11 HttpClient - Kotlin
  2. Using Java 11 HttpClient with Kotlin Coroutines
  3. HTTP Head request using Java 11 HttpClient - Kotlin
  4. REST Assured Basic Authentication
  5. 50 Java Interview Questions for SDET Automation Engineer
  6. Rest Assured API Testing Interview Questions
  7. Java Coding Problems for SDET Automation Engineer

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.