---

# Business Logic — Example.http2() [19 LOC]

| Field | Value |
|-------|-------|
| Fully Qualified Name | `io.github.biezhi.java11.http.Example` |
| Layer | Utility (Package: `io.github.biezhi.java11.http`) |
| Module | `http` (Package: `io.github.biezhi.java11.http`) |

## 1. Role

### Example.http2()

This method demonstrates how to send an **asynchronous HTTP/2 GET request** using the Java 11 `HttpClient` API. It constructs an `HttpClient` configured for HTTP/2 protocol (`HttpClient.Version.HTTP_2`) with normal redirect handling (`HttpClient.Redirect.NORMAL`), then sends a non-blocking async request to the Akamai HTTP/2 demo endpoint (`https://http2.akamai.com/demo`). The method implements the **async-completion callback pattern** via `sendAsync()` combined with `whenComplete()`, which handles both successful responses and exceptions in a single callback. It then blocks on the returned `CompletableFuture` using `.join()` until the response is fully received. This method serves as a **standalone demonstration** of Java 11's modern HTTP client capabilities — specifically HTTP/2 support, asynchronous I/O, and the callback-based response handling API. There are no conditional branches based on constants or external state; the single code path either succeeds with the response body and status code printed to stdout, or fails with the exception stack trace printed.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["http2()"])
    CONFIG["Configure HttpClient: build() with HTTP_2 version and NORMAL redirects"]
    ASYNC_SEND["Send async GET request to https://http2.akamai.com/demo"]
    CALLBACK["whenComplete callback: process response or error"]
    ERROR_CHECK{"Error occurred?"}
    ERROR_BRANCH["Print stack trace of exception"]
    SUCCESS_BRANCH["Print response body and status code"]
    WAIT[".join() - block until async completion"]
    END_NODE(["Return / Exit"])

    START --> CONFIG --> ASYNC_SEND --> CALLBACK --> ERROR_CHECK
    ERROR_CHECK -- "Yes (t != null)" --> ERROR_BRANCH --> END_NODE
    ERROR_CHECK -- "No" --> SUCCESS_BRANCH --> WAIT --> END_NODE
```

**CRITICAL — Constant Resolution:**

No external constants are referenced in this method. All values are specified inline:
- `HttpClient.Version.HTTP_2` — the HTTP/2 protocol version enum constant (Java 11 JDK-defined).
- `HttpClient.Redirect.NORMAL` — the redirect handling mode enum constant (Java 11 JDK-defined), meaning redirect only for same-host and safe methods.
- `"https://http2.akamai.com/demo"` — the Akamai HTTP/2 demo endpoint URL (inline string literal).

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| - | (none) | - | - |

**External state / instance fields read:** None. This method is `static` and operates solely on local variables and JDK API objects (`HttpClient`, `HttpRequest`, `HttpResponse`, `CompletableFuture`).

## 4. CRUD Operations / Called Services

This method does **not** perform any database CRUD operations. It calls only JDK `HttpClient` API methods:

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| N/A | `HttpClient.Builder.build()` | — | — | Creates a configured `HttpClient` instance with HTTP/2 version and redirect policy. |
| N/A | `HttpClient.sendAsync()` | — | — | Sends an asynchronous HTTP GET request to the remote Akamai demo server. |
| N/A | `HttpRequest.Builder.build()` | — | — | Constructs an immutable `HttpRequest` with URI and GET method. |
| N/A | `CompletableFuture.whenComplete()` | — | — | Registers a callback to process the response body or exception. |
| N/A | `CompletableFuture.join()` | — | — | Blocks the calling thread until the async request completes. |

## 5. Dependency Trace

| # | Caller (Screen/Batch) | Call Chain (Full Path to this Method) | Terminal (SC / CRUD / Entity) |
|---|----------------------|--------------------------------------|-------------------------------|
| 1 | (none found) | — | — |

No callers were found anywhere in the codebase. This method is a standalone example/demonstration method, not invoked by any other class in the project.

## 6. Per-Branch Detail Blocks

**Block 1** — [METHOD BODY] `(static method, throws Exception)` (L154)

> Configures and sends an async HTTP/2 GET request, then blocks until completion.

| # | Type | Code |
|---|------|------|
| 1 | SET | `HttpClient client = HttpClient.newBuilder()` — fluent builder chain begins |
| 2 | EXEC | `.followRedirects(HttpClient.Redirect.NORMAL)` — set redirect policy to NORMAL (only same-host, safe redirects) |
| 3 | EXEC | `.version(HttpClient.Version.HTTP_2)` — force HTTP/2 protocol version |
| 4 | EXEC | `.build()` — finalize and create the `HttpClient` instance |
| 5 | EXEC | `.sendAsync(HttpRequest.newBuilder()...build(), HttpResponse.BodyHandlers.ofString())` — send async GET request to `https://http2.akamai.com/demo` |
| 6 | EXEC | `.whenComplete((resp, t) -> {...})` — register completion callback for success or failure |

**Block 1.1** — [LAMBDA / CALLBACK] `((resp, t) -> { ... })` (L167)

> Handles the async response completion, branching on whether an error occurred.

| # | Type | Code |
|---|------|------|
| 1 | SET | `resp` = the `HttpResponse<String>` (null if error) |
| 2 | SET | `t` = the `Throwable` (null if success) |

**Block 1.1.1** — [IF] `(t != null)` (L168)

> Error branch: the async request failed with an exception.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `t.printStackTrace()` — print the exception stack trace to stderr |

**Block 1.1.2** — [ELSE] `(t == null)` (L170)

> Success branch: the HTTP/2 response was received successfully.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `System.out.println(resp.body())` — print the response body (HTML/demo content) to stdout |
| 2 | EXEC | `System.out.println(resp.statusCode())` — print the HTTP status code to stdout |

**Block 1.2** — [METHOD END] (L174)

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `.join()` — blocks the current thread until the `CompletableFuture` completes |
| 2 | RETURN | `void` — method returns after async operation completes (or throws the original exception if failed) |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| HTTP/2 | Protocol | HTTP/2 — second major version of the HTTP protocol, supporting multiplexed streams, header compression, and server push. |
| HttpClient | JDK Class | Java 11 `java.net.http.HttpClient` — the modern, standardized HTTP client introduced in Java 11 as a replacement for `HttpURLConnection`. |
| sendAsync() | API Method | `HttpClient.sendAsync()` — sends an HTTP request asynchronously, returning a `CompletableFuture<HttpResponse<T>>` that completes when the response is received. |
| whenComplete() | API Method | `CompletableFuture.whenComplete()` — registers a callback to run when the future completes, whether normally or exceptionally. |
| join() | API Method | `CompletableFuture.join()` — blocks the calling thread and returns the result of the async operation, throwing an unchecked exception if the operation failed. |
| HTTP_2 | Enum Value | `HttpClient.Version.HTTP_2` — forces the HTTP client to use the HTTP/2 protocol when connecting to the remote server. |
| Redirect.NORMAL | Enum Value | `HttpClient.Redirect.NORMAL` — redirect mode that follows redirects only for "safe" methods (GET, HEAD) and only to the same host. |
| Akamai | Business term | Akamai Technologies — a global Content Delivery Network (CDN) provider; `http2.akamai.com/demo` is a public endpoint maintained by Akamai to test HTTP/2 client support. |
| BodyHandlers.ofString() | API Method | `HttpResponse.BodyHandlers.ofString()` — a built-in body handler that decodes the HTTP response body into a `String` using UTF-8 encoding. |

---
