Java 11 HttpClient with Basic Authentication

Carvia Tech | October 31, 2019 | 1 min read | 2 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. Top 50 SDET Java Programming Interview Questions & Answers
  2. SDET: Rest Assured Interview Questions
  3. SDET: JUnit interview questions for automation engineer
  4. HTTP Head request using Java 11 HttpClient - Kotlin
  5. HTTP GET request with Java 11 HttpClient - Kotlin
  6. Basic Authentication using RestAssured
  7. Using Java 11 HttpClient with Kotlin Coroutines



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