Skip to main content

Lesson 5 of 8

HTTP Client - Java 11+ HttpClient

Java 11 introduced java.net.http.HttpClient - a modern, non-blocking HTTP/1.1 and HTTP/2 client built into the JDK. It replaces the old and cumbersome HttpURLConnection, with support for async requests, streaming, and WebSocket.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Java HttpClient in Practice

Java HttpClient in Practice
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;

public class HttpClientDemo {

    // Reuse client - expensive to create; thread-safe
    private static final HttpClient client = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_2)
        .connectTimeout(Duration.ofSeconds(10))
        .followRedirects(HttpClient.Redirect.NORMAL)
        .build();

    // ── Synchronous GET ──────────────────────────────────────────
    public static String getBooks(String apiUrl) throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(apiUrl))
            .header("Accept", "application/json")
            .header("Authorization", "Bearer " + getApiKey())
            .timeout(Duration.ofSeconds(5))
            .GET()
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() == 200) {
            return response.body();
        }
        throw new RuntimeException("API error: " + response.statusCode() + " - " + response.body());
    }

    // ── POST with JSON body ───────────────────────────────────────
    public static int createBook(BookDto book) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(book);

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.library.com/books"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        return response.statusCode();   // 201 Created
    }

    // ── Asynchronous request - non-blocking ───────────────────────
    public static CompletableFuture<List<BookDto>> getBooksAsync(String apiUrl) {
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(apiUrl))
            .build();

        return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .thenApply(json -> {
                try {
                    ObjectMapper mapper = new ObjectMapper();
                    return mapper.readValue(json,
                        mapper.getTypeFactory().constructCollectionType(List.class, BookDto.class));
                } catch (Exception e) {
                    throw new RuntimeException("JSON parse error", e);
                }
            });
    }

    // ── Parallel requests ─────────────────────────────────────────
    public static void fetchMultiple(List<String> urls) throws Exception {
        List<CompletableFuture<String>> futures = urls.stream()
            .map(url -> client.sendAsync(
                HttpRequest.newBuilder(URI.create(url)).build(),
                HttpResponse.BodyHandlers.ofString()
            ).thenApply(HttpResponse::body))
            .toList();

        CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join();
        futures.stream().map(CompletableFuture::join).forEach(System.out::println);
    }

    private static String getApiKey() { return System.getenv("API_KEY"); }
}

Quick Quiz

Tip

Tip

Practice HTTP Client Java 11 HttpClient in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for HTTP Client - Java 11+ HttpClient

Practice Task

Note

Practice Task - (1) Write a working example of HTTP Client Java 11 HttpClient from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with HTTP Client Java 11 HttpClient is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.

Topics in This Module

0/8 done