Grundlegende Authentifizierung mit 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

Grundlegende Authentifizierung mit Java 11 HttpClient
Ich habe versucht, eine Standardauthentifizierung mit Java durchzuführen
Implementieren Sie die Standardauthentifizierung in Java
Informationen zur Signaturauthentifizierung mit Java Time 1
Profilerstellung mit Java Visual VM ~ Grundlegende Verwendung ~
Grundlegende Java-Grammatik
Grundlegende Java-Grammatik
Parallelitätsmethode in Java mit grundlegendem Beispiel
Java Grundkenntnisse 1
[Java] Grundstruktur
[Java] [Basic] Glossar
Grundlegende Java-Grammatik
Der Suchtpunkt bei der Durchführung der Basisauthentifizierung mit Java URLConnection
Grundlegende Java-Grammatik
Java-Übung [Basic]
Erreichen Sie die BASIC-Authentifizierung mit Spring Boot + Spring Security
So schreiben Sie Testcode mit Basic-Zertifizierung
Installieren Sie Java mit Homebrew
Wechseln Sie die Plätze mit Java
Installieren Sie Java mit Ansible
Java Grundwissen Memo
[Java] Datentyp ①-Basistyp
Bequemer Download mit JAVA
Grundlegende Java-Datumsmanipulation
Schalten Sie Java mit direnv
Grundlegende Java-Namenskonventionen
Java-Lernnotiz (grundlegend)
Java-Download mit Ansible
Lass uns mit Java kratzen! !!
Erstellen Sie Java mit Wercker
[Java] Grundlegende Methodenhinweise
Java-Grunddatentypen
Grundlegende Java OOps-Konzepte
Endian-Konvertierung mit JAVA
Führen Sie nach der Standardauthentifizierung mit Spring Boot eine beliebige Verarbeitung aus.
[Anfänger] Erstellen Sie ein wettbewerbsfähiges Spiel mit grundlegenden Java-Kenntnissen
Suche nach POST-Anforderung mit Azure Search + Java Apache HttpClient
(Java) Einfache BDD mit Spektrum?
Verwenden Sie Lambda-Ebenen mit Java
Erstellen Sie mit Gradle ein Java-Multiprojekt
Java Basic Learning Content 7 (Ausnahme)
Java-Konfiguration mit Spring MVC
Experimentieren wir mit der Java-Inline-Erweiterung
Java-Basissyntax + α-Trap
Führen Sie Batch mit Docker-Compose mit Java-Batch aus
[Vorlage] MySQL-Verbindung mit Java
Schreiben Sie Java Try-Catch mit Optional neu
Installieren Sie Java 7 mit Homebrew (Fass)
[Java] JSON-Kommunikation mit Jackson
Java zum Spielen mit Function
Versuchen Sie eine DB-Verbindung mit Java
[Java] Grundlegende Aussage für Anfänger
Aktivieren Sie Java EE mit NetBeans 9
Java Basic Learning Content 5 (Qualifikation)
[Java] JavaConfig mit statischer innerer Klasse
Versuchen Sie gRPC mit Java, Maven
Lassen Sie uns Excel mit Java betreiben! !!
So führen Sie die Standardauthentifizierung ein
Java-Versionsverwaltung mit SDKMAN
RSA-Verschlüsselung / Entschlüsselung mit Java 8
Paging PDF mit Java + PDFBox.jar