Java 11 HttpClient with Basic Authentication

Carvia Tech | December 01, 2019 | 1 min read | 869 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()
            .authenticator(object : Authenticator() {   (1)
                override fun getPasswordAuthentication(): PasswordAuthentication {
                    return PasswordAuthentication("admin", "password".toCharArray())

    val request = HttpRequest.newBuilder()

    val httpResponse = httpClient.send(request, BodyHandlers.ofString())
    println("httpResponse statusCode = ${httpResponse.statusCode()}")
1 PasswordAuthentication is configured for handling HTTP Basic Authentication.
HttpClient - async client
httpClient.sendAsync(request, BodyHandlers.ofString())
Server Response
httpResponse statusCode = 200

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:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info