# Business Logic — Example.asyncGet() [16 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.asyncGet()

This method demonstrates how to perform an **asynchronous HTTP GET request** using Java 11's built-in `java.net.http.HttpClient` API. It accepts a URI string, constructs an HTTP client and a corresponding request, dispatches the request asynchronously via `sendAsync()`, and blocks the calling thread until the response is received by calling `.join()` on the `CompletableFuture`. The method acts as a **self-contained demonstration utility** — it is part of the `Example` class, which is a collection of code samples illustrating Java 11 HTTP client features. It does not integrate with any enterprise service layer, SC components, or database operations. Its role in the system is purely illustrative, showing developers how to leverage the non-blocking HTTP client API for parallel request execution without tying up threads. The method implements a **fire-and-wait** pattern: the request is dispatched non-blockingly, but the caller explicitly waits for the single response before proceeding.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["asyncGet(uri)"])
    CREATE_CLIENT["Create new HttpClient"]
    BUILD_REQUEST["Build HttpRequest via HttpRequest.newBuilder()"]
    SET_URI["Set URI from parameter uri"]
    SEND_ASYNC["Send async request via client.sendAsync()"]
    WHEN_COMPLETE["Register completion handler via whenComplete()"]
    CHECK_ERROR["Is exception non-null?"]
    LOG_ERROR["Print exception stack trace"]
    LOG_RESPONSE["Print response body and status code"]
    JOIN_WAIT["Wait for completion via .join()"]
    END_NODE(["Return void / Next"])

    START --> CREATE_CLIENT
    CREATE_CLIENT --> BUILD_REQUEST
    BUILD_REQUEST --> SET_URI
    SET_URI --> SEND_ASYNC
    SEND_ASYNC --> WHEN_COMPLETE
    WHEN_COMPLETE --> CHECK_ERROR
    CHECK_ERROR -- "No exception" --> LOG_RESPONSE
    CHECK_ERROR -- "Exception exists" --> LOG_ERROR
    LOG_RESPONSE --> END_NODE
    LOG_ERROR --> END_NODE
```

**Description of flow:**

1. A new `HttpClient` instance is created via `HttpClient.newHttpClient()`. Each call creates an independent client with default settings (no connection pooling, no shared state across calls).
2. An `HttpRequest` is built using the fluent `HttpRequest.newBuilder()` API. The request URI is set from the `uri` parameter via `URI.create(uri)`. No additional headers, method modifiers, or body content are configured — it is a plain HTTP GET request.
3. The async request is dispatched via `client.sendAsync(request, HttpResponse.BodyHandlers.ofString())`, which returns a `CompletableFuture<HttpResponse<String>>`. The response body is handled as a UTF-8 `String`.
4. A completion handler (`whenComplete`) is registered on the `CompletableFuture`. This handler receives either the response (`resp`) or an exception (`t`). If an exception occurred, its stack trace is printed. Otherwise, the response body and status code are printed to standard output.
5. `.join()` is called on the `CompletableFuture`, which blocks the calling thread until the async operation completes (either successfully or exceptionally). This transforms the non-blocking async call into a synchronous-wait pattern for this specific invocation.

**Note: No constants are used in this method. The flow is linear with a single conditional branch inside the completion handler.**

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| 1 | `uri` | `String` | The target HTTP URL to which the GET request will be sent. Represents a web resource endpoint (e.g., an API endpoint, a static resource URL, or a web page). The string is passed through `URI.create()`, so it must be a valid RFC 2396-compliant URI. Invalid URIs will cause a `IllegalArgumentException` at request construction time. |

**External/Instance State Read:**
- None — this method is `static` and does not reference any instance fields. It creates all state (HttpClient, HttpRequest, CompletableFuture) locally.

## 4. CRUD Operations / Called Services

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| — | `HttpClient.newHttpClient()` | — | — | Creates a new HTTP client instance (not a CRUD operation; infrastructure setup) |
| — | `HttpRequest.newBuilder()` | — | — | Constructs a new HTTP request builder (not a CRUD operation; request preparation) |
| R | `client.sendAsync()` | — | — | Sends an asynchronous HTTP GET request to the remote server and reads the response body as a String |

**Note:** This method operates at the raw HTTP protocol level and does not interact with any enterprise service components (SC), CBS, or database tables. It performs a single remote read (HTTP GET) to an external system.

## 5. Dependency Trace

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

**Note:** `asyncGet` is a static demonstration method in the `Example` class. No callers were found in the codebase. It is intended for reference/learning purposes only and is not invoked by any screen, batch, or service component.

## 6. Per-Branch Detail Blocks

**Block 1** — [EXEC] `HttpClient` creation (L44)

| # | Type | Code |
|---|------|------|
| 1 | CALL | `HttpClient.newHttpClient()` // Creates a new default HTTP client instance for the request |

**Block 2** — [EXEC] `HttpRequest` construction (L45–47)

| # | Type | Code |
|---|------|------|
| 1 | CALL | `HttpRequest.newBuilder()` // Initiates a fluent request builder |
| 2 | CALL | `.uri(URI.create(uri))` // Sets the target URI from the method parameter |
| 3 | CALL | `.build()` // Finalizes and returns an immutable HttpRequest object |

**Block 3** — [EXEC] Async request dispatch (L49)

| # | Type | Code |
|---|------|------|
| 1 | CALL | `client.sendAsync(request, HttpResponse.BodyHandlers.ofString())` // Sends the request asynchronously and returns a CompletableFuture<HttpResponse<String>> |

**Block 4** — [EXEC] Completion handler registration and blocking wait (L50–57)

| # | Type | Code |
|---|------|------|
| 1 | CALL | `responseCompletableFuture.whenComplete((resp, t) -> { ... })` // Registers a handler invoked on either success or failure |

**Block 4.1** — [IF] Exception check (L51) (condition: `t != null`)

> When an exception occurred during the async request, print its stack trace for diagnostic purposes.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `t.printStackTrace()` // Prints the exception stack trace to standard error |

**Block 4.2** — [ELSE-IF] Success branch (L52) (condition: `t == null`, i.e., no exception)

> When the request completes successfully, print the response body and HTTP status code to standard output.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `System.out.println(resp.body())` // Prints the HTTP response body (String) |
| 2 | EXEC | `System.out.println(resp.statusCode())` // Prints the HTTP response status code (int) |

**Block 5** — [EXEC] Synchronous wait (L57)

| # | Type | Code |
|---|------|------|
| 1 | CALL | `.join()` // Blocks the calling thread until the CompletableFuture completes |

**Block 6** — [RETURN] Method return (L58)

| # | Type | Code |
|---|------|------|
| 1 | RETURN | `void` // Method completes; caller resumes after .join() |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `uri` | Parameter | Uniform Resource Identifier — the web address of the HTTP resource to be fetched via GET request |
| `HttpClient` | Class | Java 11 non-blocking HTTP client — a modern replacement for `HttpURLConnection`, supporting both synchronous and asynchronous request execution |
| `HttpRequest` | Class | Immutable HTTP request model — encapsulates the URI, headers, method type, and optional body of an HTTP request |
| `sendAsync()` | Method | Sends an HTTP request asynchronously — returns a `CompletableFuture` that completes when the response is available, without blocking the calling thread |
| `CompletableFuture` | Class | Java utility for asynchronous programming — represents a future result that may be completed by another thread |
| `whenComplete()` | Method | Registers a handler to run when the `CompletableFuture` completes (either normally or exceptionally) — enables non-blocking response processing |
| `.join()` | Method | Blocks the calling thread until the `CompletableFuture` completes — returns the result or re-throws the exception |
| `HttpResponse` | Class | Java 11 HTTP response model — encapsulates the status code, headers, and body of an HTTP response |
| `BodyHandlers.ofString()` | Method | A response body handler that reads the full HTTP response body as a UTF-8 encoded String |
| `URI.create()` | Method | Parses a String into a `java.net.URI` object — throws `IllegalArgumentException` if the string is not a valid URI |
