Basic Authentication with Java 11 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 a reference implementation. Spring Boot 2 based Basic Auth Server 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.

fun basicAuthSync() {
    val httpClient: HttpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .authenticator(object : Authenticator() {   
                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())
}

PasswordAuthentication is configured for handling HTTP Basic Authentication.

httpClient.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse<String>::body)
        .thenAccept(System.out::println)
        .join()
Server Response
httpResponse statusCode = 200
{"status":"UP"}

What's new in Spring Boot 2 Spring boot 2 is liberated from legacy baggage of deprecated Java releases. Java 8 is the minimum baseline, with Java 9 support. Under the hood Spring Boot, 2 uses Spring 5. Reactive web programming support with Spring Webflux. Auto-configuration and starter POMs for reactive Spring Data Cassandra, MongoDB, Couchbase and Redis. Supports embedded Netty, along with HTTP/2 support for Tomcat, Undertow, and Jetty Kotlin we supported in Spring Boot 2, along with Junit 5. Now you can write Spring Boot 2 application from scratch in Kotlin.  A brand new actuator architecture, with support for Spring MVC, WebFlux and Jersey. Simplified security auto-configuration. Uses Spring Framework 5 under the hood. Gradle 4 required, works well with Gradle 5.

Related blog:

Best Java training in chennai

Recommended Posts

Basic Authentication with Java 11 HttpClient
I tried to make Basic authentication with Java
Implement Basic authentication in Java
About signature authentication with java 1st
Profiling with Java Visual VM ~ Basic usage ~
Java basic grammar
Java basic grammar
Concurrency Method in Java with basic example
Java basic knowledge 1
[Java] Basic structure
[Java] [Basic] Glossary
Java basic grammar
The point of addiction when performing basic authentication with Java URLConnection
Java basic grammar
Java exercises [Basic]
Achieve BASIC authentication with Spring Boot + Spring Security
How to write test code with Basic authentication
Install java with Homebrew
Change seats with java
Install Java with Ansible
java basic knowledge memo
[Java] Data type ①-Basic type
Comfortable download with JAVA
Java basic date manipulation
Switch java with direnv
Java basic naming conventions
Java learning memo (basic)
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
[Java] Basic method notes
Java basic data types
Basic Java OOps concepts
Endian conversion with JAVA
Execute arbitrary processing after Basic authentication with Spring boot.
[Beginner] Create a competitive game with basic Java knowledge
Search by POST request with Azure Search + Java Apache HttpClient
Easy BDD with (Java) Spectrum?
Use Lambda Layers with Java
Java multi-project creation with Gradle
Java basic learning content 7 (exception)
Java Config with Spring MVC
Let's experiment with Java inlining
Java basic syntax + α trap
Run batch with docker-compose with Java batch
[Template] MySQL connection with Java
Rewrite Java try-catch with Optional
Install Java 7 with Homebrew (cask)
[Java] JSON communication with jackson
Java to play with Function
Try DB connection with Java
[Java] Basic statement for beginners
Enable Java EE with NetBeans 9
Java basic learning content 5 (modifier)
[Java] JavaConfig with Static InnerClass
Try gRPC with Java, Maven
Let's operate Excel with Java! !!
How to introduce Basic authentication
Version control Java with SDKMAN
RSA encryption / decryption with java 8
Paging PDF with Java + PDFBox.jar