Java 11 HttpClient with Basic Authentication

Carvia Tech | 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 SDET Java Interview Questions & Answers
  6. Rest Assured API Testing Interview Questions
  7. SDET: JUnit interview questions for automation engineer

Find more on this topic:

Recommended books for interview preparation: