---

# (DD02) Business Logic — Example.asyncPost() [25 LOC]

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

## 1. Role

### Example.asyncPost()

This method demonstrates an asynchronous HTTP POST request flow using the Java 11 HTTP client. It constructs a sample payload object, converts it into JSON, submits the payload to an external HTTP endpoint, and waits for the asynchronous exchange to finish before the method exits. Business-wise, it acts as a client-side integration example for posting structured request data to a remote service and observing the response outcome.

The method follows a simple orchestration and delegation pattern: object preparation, serialization, request construction, asynchronous dispatch, and completion handling. It does not branch into multiple business service types, but it does separate success and failure handling inside the completion callback. In the larger system, it serves as a utility/demo entry point that shows how to execute non-blocking outbound HTTP communication and how to inspect the returned payload and status code.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START["asyncPost()"]
    C1{"Create HttpClient"}
    C2{"Instantiate Gson and Foo"}
    C3{"Set Foo fields"}
    C4{"Serialize Foo to JSON"}
    C5{"Build HttpRequest for POST /post"}
    C6{"Send request asynchronously"}
    C7{"Completion callback"}
    C8{"Throwable present?"}
    C9["Print stack trace"]
    C10["Print response body and status code"]
    END_NODE["Join completion and return"]
    START --> C1
    C1 --> C2
    C2 --> C3
    C3 --> C4
    C4 --> C5
    C5 --> C6
    C6 --> C7
    C7 --> C8
    C8 -- "Yes" --> C9
    C8 -- "No" --> C10
    C9 --> END_NODE
    C10 --> END_NODE
```

**CRITICAL — Constant Resolution:**
No project constants or constant-based branches are used in this method. The endpoint URL and header values are inline literals.

## 3. Parameter Analysis

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

External state read by the method:
- `HttpClient.newHttpClient()` creates the outbound HTTP client instance.
- `Gson` is instantiated locally for JSON serialization.
- `Foo` is instantiated locally as the request payload model.
- The method uses the fixed target URL `https://httpbin.org/post`.
- The method uses the fixed request header `Content-Type: application/json`.
- The method reads response body and status code only when the asynchronous call completes successfully.

## 4. CRUD Operations / Called Services

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| C | `sendAsync()` | N/A | N/A | Sends a new outbound HTTP POST request asynchronously to the remote endpoint. |
| R | `whenComplete()` | N/A | N/A | Observes the completion result of the outbound call and reads the response body and status code on success. |

Notes:
- `sendAsync()` is an external network interaction rather than an internal CRUD service, so it is classified as a create-style outbound action.
- No internal SC/CBS method, database table, or entity access is present in the method body.

## 5. Dependency Trace

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

No screen/batch entry points found within 8 hops. Direct callers found: 1 methods.
Terminal operations from this method: -

| # | Caller (Screen/Batch) | Call Chain (Full Path to this Method) | Terminal (SC / CRUD / Entity) |
|---|----------------------|--------------------------------------|-------------------------------|
| 1 | `Example.main()` | `Example.main()` -> `Example.asyncPost()` | `sendAsync() [C] N/A` |

## 6. Per-Branch Detail Blocks

**Block 1** — [SET] (L61)

> Initialize the asynchronous HTTP client used for outbound communication.

| # | Type | Code |
|---|------|------|
| 1 | SET | `HttpClient client = HttpClient.newHttpClient();` |

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

> Prepare the JSON serializer and the sample business payload.

| # | Type | Code |
|---|------|------|
| 1 | SET | `Gson gson = new Gson();` |
| 2 | SET | `Foo foo = new Foo();` |
| 3 | SET | `foo.name = "王爵nice";` |
| 4 | SET | `foo.url = "https://github.com/biezhi";` |

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

> Convert the sample payload into a JSON request body.

| # | Type | Code |
|---|------|------|
| 1 | SET | `String jsonBody = gson.toJson(foo);` |

**Block 4** — [SET] (L70-L74)

> Build the HTTP POST request to the fixed remote endpoint with JSON content type.

| # | Type | Code |
|---|------|------|
| 1 | SET | `HttpRequest request = HttpRequest.newBuilder()` |
| 2 | EXEC | `.uri(new URI("https://httpbin.org/post"))` |
| 3 | EXEC | `.header("Content-Type", "application/json")` |
| 4 | EXEC | `.POST(HttpRequest.BodyPublishers.ofString(jsonBody))` |
| 5 | EXEC | `.build();` |

**Block 5** — [CALL] (L75-L82)

> Dispatch the request asynchronously and attach completion handling for success and failure.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `client.sendAsync(request, HttpResponse.BodyHandlers.ofString())` |
| 2 | CALL | `.whenComplete((resp, t) -> { ... })` |
| 3 | IF | `if (t != null)` |

**Block 5.1** — [IF] (`t != null`) (L76)

> Handle the failure path for the asynchronous request.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `t.printStackTrace();` |

**Block 5.2** — [ELSE] (`t == null`) (L78-L81)

> Handle the success path by printing the response content and HTTP status.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `System.out.println(resp.body());` |
| 2 | EXEC | `System.out.println(resp.statusCode());` |

**Block 6** — [CALL] (L82)

> Wait for the asynchronous exchange to finish before returning from the method.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `.join();` |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `asyncPost` | Method name | Asynchronous POST demonstration method that submits JSON to a remote HTTP endpoint and waits for completion. |
| `HttpClient` | Technical term | Java 11 HTTP client used to send outbound network requests. |
| `HttpRequest` | Technical term | Immutable outbound request definition containing URI, headers, and body publisher. |
| `HttpResponse` | Technical term | Response wrapper returned by the remote endpoint, including body and status code. |
| `sendAsync` | Technical term | Non-blocking HTTP call that starts the request and returns a completion stage. |
| `whenComplete` | Technical term | Completion callback hook that runs after the asynchronous call finishes, regardless of success or failure. |
| `join` | Technical term | Blocking wait that ensures the async call completes before the method exits. |
| `Gson` | Technical term | JSON serialization library used to convert the payload object into a request body. |
| `Foo` | DTO / Model | Sample payload object containing `name` and `url` fields for the outbound JSON body. |
| `name` | Field | Person or subject name included in the sample JSON request body. |
| `url` | Field | Web address included in the sample JSON request body. |
| `Content-Type` | HTTP header | Declares that the request body is formatted as JSON. |
| `application/json` | MIME type | Standard content type for JSON-formatted HTTP payloads. |
| `httpbin.org/post` | External service endpoint | Public test endpoint that echoes HTTP POST requests for integration demonstration. |
| `statusCode` | Response property | Numeric HTTP status returned by the remote service, used to confirm the outcome of the call. |
| `body` | Response property | Response payload returned by the remote service, printed on success. |
| `Throwable` (`t`) | Java error type | Captures any exception or failure produced by the asynchronous call. |

