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

This method demonstrates **asynchronous HTTP POST** usage in Java 11's built-in `HttpClient` API. It constructs a JSON payload from a `Foo` data object, builds an HTTP POST request targeting `https://httpbin.org/post`, and sends it asynchronously via `HttpClient.sendAsync()`. The method implements the **builder pattern** for request construction (`HttpRequest.newBuilder()`) and the **future/callback pattern** for asynchronous execution (`CompletableFuture.whenComplete()`). Its role in the larger system is that of a **self-contained demo/illustration method** — it is not called by any other business logic but is invoked directly from the `main()` entry point of the `Example` class as one of several HTTP demonstration methods (alongside `syncGet`, `asyncGet`, `http2`, and `downloadFile`). The method's source code comment, "异步调用 POST" (Asynchronous POST call), confirms its purpose is to showcase the non-blocking POST pattern in Java 11.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["asyncPost Entry"])
    CREATE_CLIENT["Create HttpClient instance"]
    CREATE_GSON["Create Gson instance"]
    CREATE_FOO["Create Foo object and set fields name and url"]
    SERIALIZE["Serialize Foo to JSON string"]
    BUILD_REQUEST["Build HttpRequest POST to httpbin.org/post with JSON body"]
    SEND_ASYNC["Send request asynchronously"]
    WHEN_COMPLETE["Register whenComplete callback"]
    CHECK_ERROR{"Error present?"}
    PRINT_ERROR["Print exception stack trace"]
    PRINT_RESPONSE["Print response body and status code"]
    JOIN["Await completion via join"]
    END_NODE(["Return"])

    START --> CREATE_CLIENT
    CREATE_CLIENT --> CREATE_GSON
    CREATE_GSON --> CREATE_FOO
    CREATE_FOO --> SERIALIZE
    SERIALIZE --> BUILD_REQUEST
    BUILD_REQUEST --> SEND_ASYNC
    SEND_ASYNC --> WHEN_COMPLETE
    WHEN_COMPLETE --> CHECK_ERROR
    CHECK_ERROR -- "Yes" --> PRINT_ERROR --> JOIN
    CHECK_ERROR -- "No" --> PRINT_RESPONSE --> JOIN
    JOIN --> END_NODE
```

**Processing Flow Summary:**

1. **HttpClient Creation**: Creates a new `HttpClient` instance using the static factory `HttpClient.newHttpClient()`, which uses the default configuration (no proxy, default connect timeout, HTTP/2 support).
2. **Gson Initialization**: Instantiates a `Gson` object for JSON serialization.
3. **Payload Construction**: Creates a `Foo` object and populates it with hardcoded values: `name` is set to `"王爵nice"` (the string literal value), and `url` is set to `"https://github.com/biezhi"`.
4. **JSON Serialization**: Converts the `Foo` object to a JSON string via `gson.toJson(foo)`.
5. **Request Building**: Uses the builder pattern to construct an `HttpRequest` targeting `https://httpbin.org/post` with `Content-Type: application/json` header and the JSON string as the POST body.
6. **Asynchronous Dispatch**: Sends the request asynchronously via `client.sendAsync(request, HttpResponse.BodyHandlers.ofString())`, which returns a `CompletableFuture<HttpResponse<String>>`.
7. **Callback Registration**: Registers a `whenComplete` callback to handle both success and error outcomes.
8. **Result Handling (Branch)**:
   - **Error branch**: If the future completes exceptionally, the stack trace is printed.
   - **Success branch**: If the future completes normally, the response body and status code are printed to stdout.
9. **Blocking Wait**: Calls `.join()` on the `CompletableFuture` to block the calling thread until the asynchronous operation completes (note: the method itself throws `Exception` to allow the CompletableFuture exception to propagate if the join encounters one).
10. **Return**: Returns `void`.

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| - | (none) | - | This is a static method with no parameters. |
| 1 | (implicit) | `Foo` fields | The method internally constructs a `Foo` object with two String fields: `name` (a free-form text label, hardcoded to `"王爵nice"`) and `url` (a URL string, hardcoded to `"https://github.com/biezhi"`). These fields are serialized as a JSON object in the HTTP POST body. |

**External State Read:**
- `HttpClient` (Java 11 built-in): Provides the underlying network client for sending HTTP requests.
- `Gson` (Google Gson library): Used for serializing the `Foo` Java object into a JSON-formatted string.

## 4. CRUD Operations / Called Services

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| N/A | `client.sendAsync()` | N/A | N/A | Asynchronous HTTP POST to external endpoint (httpbin.org) — no enterprise CRUD operation; this is a network call to a public HTTP testing service that echoes back the posted data. |

**Notes:** This method does not interact with any enterprise service components (SC), business services (CBS), or database tables. It is a pure HTTP demonstration method that calls `https://httpbin.org/post`, a public web service used for testing HTTP requests. `httpbin.org` echoes back the request details in its response but does not persist or query any enterprise data.

## 5. Dependency Trace

### Pre-computed evidence from code analysis graph:

No screen/batch entry points found within 8 hops. Direct callers found: 1 methods.

This method is called directly from the `main()` entry point of the `Example` class, which serves as the primary demonstration entry point for all HTTP client examples in this file.

| # | Caller (Screen/Batch) | Call Chain (Full Path to this Method) | Terminal (SC / CRUD / Entity) |
|---|----------------------|--------------------------------------|-------------------------------|
| 1 | Entry: `main(String[])` | `Example.main` -> `Example.asyncPost` | `sendAsync [N/A] httpbin.org/post (external HTTP)` |

## 6. Per-Branch Detail Blocks

**Block 1** — [SET/INITIALIZATION] (L62)

> Creates the HTTP client and Gson instance for JSON processing.

| # | Type | Code |
|---|------|------|
| 1 | SET | `HttpClient client = HttpClient.newHttpClient()` // Create default HTTP client |
| 2 | SET | `Gson gson = new Gson()` // Create JSON serializer |

**Block 2** — [SET/OBJECT CONSTRUCTION] (L63-L66)

> Constructs and populates the `Foo` data object with hardcoded payload values.

| # | Type | Code |
|---|------|------|
| 1 | SET | `Foo foo = new Foo()` // Instantiate data object |
| 2 | SET | `foo.name = "王爵nice"` // Set name field (Chinese characters: "Prince Wang nice") |
| 3 | SET | `foo.url = "https://github.com/biezhi"` // Set URL field pointing to the author's GitHub |

**Block 3** — [SET/SERIALIZATION] (L68)

> Serializes the `Foo` object into a JSON string to form the HTTP POST body.

| # | Type | Code |
|---|------|------|
| 1 | SET | `String jsonBody = gson.toJson(foo)` // Serialize Foo -> JSON string |

**Block 4** — [SET/REQUEST BUILDING] (L70-L76)

> Builds the HTTP POST request using the builder pattern, specifying URI, headers, and body.

| # | Type | Code |
|---|------|------|
| 1 | SET | `HttpRequest request = HttpRequest.newBuilder()...build()` // Builder-pattern request construction |
| 2 | EXEC | `.uri(new URI("https://httpbin.org/post"))` // Target URI |
| 3 | EXEC | `.header("Content-Type", "application/json")` // Set content type header |
| 4 | EXEC | `.POST(HttpRequest.BodyPublishers.ofString(jsonBody))` // Attach JSON string as POST body |
| 5 | EXEC | `.build()` // Finalize HttpRequest object |

**Block 5** — [EXEC/ASYNC DISPATCH + CALLBACK + BLOCKING WAIT] (L77-L85)

> Sends the request asynchronously, registers a completion callback that branches on error/success, then blocks on join.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `client.sendAsync(request, HttpResponse.BodyHandlers.ofString())` // Async dispatch, returns CompletableFuture |
| 2 | EXEC | `.whenComplete((resp, t) -> { ... })` // Register callback for both success and error completion |
| 3 | EXEC | `.join()` // Block calling thread until async operation finishes |

**Block 5.1** — [IF] `(t != null)` [Error branch of callback] (L78-L80)

> When the asynchronous operation completes exceptionally, print the stack trace.

| # | Type | Code |
|---|------|------|
| 1 | SET | `Throwable t` (passed as second lambda parameter) // Represents the async error |
| 2 | EXEC | `t.printStackTrace()` // Print stack trace to stderr |

**Block 5.2** — [ELSE] `(t == null)` [Success branch of callback] (L81-L84)

> When the asynchronous operation completes successfully, print the response body and status code.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `System.out.println(resp.body())` // Print the full response body from httpbin.org |
| 2 | EXEC | `System.out.println(resp.statusCode())` // Print the HTTP status code (e.g., 200) |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `HttpClient` | Class | Java 11 built-in HTTP client (`java.net.http.HttpClient`) — provides synchronous and asynchronous HTTP request capabilities. |
| `HttpRequest` | Class | Java 11 HTTP request object (`java.net.http.HttpRequest`) — immutable request definition with URI, headers, and body. |
| `HttpResponse` | Class | Java 11 HTTP response object (`java.net.http.HttpResponse`) — contains response body, status code, and headers returned from a server. |
| `CompletableFuture` | Class | Java concurrency construct (`java.util.concurrent.CompletableFuture`) — represents a future result of an asynchronous computation, supports callback chains via `whenComplete()`. |
| `sendAsync()` | Method | Asynchronous HTTP dispatch method on `HttpClient` — returns a `CompletableFuture` that completes when the response is received, non-blocking. |
| `whenComplete()` | Method | Callback registration on `CompletableFuture` — executes a handler when the future completes, whether normally (response) or exceptionally (error). |
| `join()` | Method | Blocking wait on `CompletableFuture` — suspends the calling thread until the async operation completes and returns the result. |
| `Gson` | Library | Google Gson library — JSON serialization/deserialization library for Java objects. |
| `Foo` | Class | Internal demo data class with `name` (String label) and `url` (String URL) fields, used as the POST request body. |
| `httpbin.org` | External service | Public HTTP testing service at `https://httpbin.org/post` that echoes back the details of POSTed requests (used here for demonstration, not production). |
| 异步调用 POST (Asynchronous POST call) | Comment | Chinese comment describing this method as an asynchronous POST invocation demo. |
| `王爵nice` | Literal string | Hardcoded name value — Chinese characters "王爵" meaning "Prince/Noble Lord" combined with English "nice". |
| Biezhi | Name | The repository author's nickname; the GitHub URL `https://github.com/biezhi` points to their public profile. |
