$ ./gradlew bootRun
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.
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.
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.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse<String>::body)
.thenAccept(System.out::println)
.join()
httpResponse statusCode = 200
{"status":"UP"}
That’s all.
Top articles in this category:
- HTTP GET request with Java 11 HttpClient - Kotlin
- Using Java 11 HttpClient with Kotlin Coroutines
- HTTP Head request using Java 11 HttpClient - Kotlin
- REST Assured Basic Authentication
- 50 Java Interview Questions for SDET Automation Engineer
- Rest Assured API Testing Interview Questions
- Java Coding Problems for SDET Automation Engineer