---
title: "Example.uploadFile() — File Upload via Java 11 HttpClient"
created: 2026-06-24
updated: 2026-06-24
---

# Business Logic — Example.uploadFile() [12 LOC]

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

## 1. Role

### Example.uploadFile()

The `uploadFile()` method demonstrates how to perform an HTTP POST request that uploads a local file to a remote HTTP server using the Java 11 HttpClient API. Specifically, it reads a text file (`/tmp/files-to-upload.txt`) from the local filesystem, wraps it as the request body of an HTTP POST request targeting `http://localhost:8080/upload/`, and sends it synchronously to the server. This method serves as a **code example** within a collection of Java 11 HTTP Client usage patterns — alongside `syncGet`, `asyncGet`, `asyncPost`, `downloadFile`, `proxy`, `basicAuth`, `http2`, and `getURIs` — all documented under the class-level Javadoc: "HTTP Client examples for Java 11" (Java 11のHttp Clientの例). It is **not** a business service method but a standalone utility demonstration intended for learning or reference, authored by `biezhi` on 2018/7/10. The method implements the **delegation pattern** by creating a fresh `HttpClient` and `HttpRequest` instance per invocation, delegating all network I/O to the JDK's built-in `java.net.http` module.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["uploadFile()"])
    CREATE_CLIENT["Create HttpClient instance
(HttpClient.newHttpClient())"]
    BUILD_URI["Build URI
(http://localhost:8080/upload/)"]
    BUILD_REQUEST["Build HttpRequest POST request
Body: ofFile(/tmp/files-to-upload.txt)"]
    SEND_REQUEST["Send request synchronously
(client.send(..., BodyHandlers.discarding()))"]
    PRINT_STATUS["Print response statusCode
(System.out.println(...))"]
    END_NODE(["Return / Next"])

    START --> CREATE_CLIENT
    CREATE_CLIENT --> BUILD_URI
    BUILD_URI --> BUILD_REQUEST
    BUILD_REQUEST --> SEND_REQUEST
    SEND_REQUEST --> PRINT_STATUS
    PRINT_STATUS --> END_NODE
```

**Processing flow:**
1. **Create HttpClient** — A new default `HttpClient` instance is created via `HttpClient.newHttpClient()`. This creates a client using the default configuration (no custom timeout, no proxy, no auth).
2. **Build URI** — The target URI `http://localhost:8080/upload/` is constructed as a `java.net.URI`.
3. **Build HttpRequest** — An `HttpRequest` is constructed via the builder pattern (`HttpRequest.newBuilder()`), setting the URI, specifying a POST method with the request body sourced from the file `/tmp/files-to-upload.txt` via `HttpRequest.BodyPublishers.ofFile()`, and building the final request object.
4. **Send request synchronously** — The request is sent on the calling thread using `client.send(request, HttpResponse.BodyHandlers.discarding())`. The response body is discarded (not stored), as only the status code is needed.
5. **Print status code** — The HTTP status code from the response is printed to stdout.
6. **Return** — The method returns `void` after printing.

No conditional branches or loops exist in this method. The flow is strictly linear.

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| - | (none) | - | This method takes no parameters. All values are hardcoded. |

**Instance fields / external state read:**
| Source | Description |
|--------|-------------|
| None | This method does not read any instance fields. It creates all objects locally. |

**Hardcoded values used internally:**
| Value | Context | Description |
|-------|---------|-------------|
| `http://localhost:8080/upload/` | Request URI | Target server endpoint for file upload |
| `/tmp/files-to-upload.txt` | Request body file | Local filesystem path of the file to upload |

## 4. CRUD Operations / Called Services

This method does not invoke any internal service components, DAOs, or business services. It directly uses the JDK 11 `java.net.http.HttpClient` API to perform a raw HTTP request.

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| External | `HttpClient.send()` | N/A (JDK API) | N/A | Sends an HTTP POST request to upload a file to `http://localhost:8080/upload/`. This is an external HTTP call, not an internal CRUD operation. |

## 5. Dependency Trace

| # | Caller (Screen/Batch) | Call Chain (Full Path to this Method) | Terminal (SC / CRUD / Entity) |
|---|----------------------|--------------------------------------|-------------------------------|
| 1 | N/A (standalone example) | No callers found. This method is a standalone demonstration method, not called by any other code in the codebase. | `HttpClient.send() -> HTTP POST to localhost:8080` |

**Note:** The `main()` method in `Example.java` does not call `uploadFile()`. Only `asyncPost()` is invoked in `main()` (line 190). The `uploadFile()` method exists solely as a code example for Java 11 HttpClient usage and is intended to be called manually or referenced by developers learning the API.

## 6. Per-Branch Detail Blocks

**Block 1** — EXEC (create HttpClient) (L105)

> Creates a default HttpClient instance using the JDK 11 static factory method. No configuration parameters (timeout, proxy, redirect policy) are set — all use platform defaults.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `HttpClient client = HttpClient.newHttpClient();` // Create default HTTP client |

**Block 2** — EXEC (build URI and HttpRequest) (L107–110)

> Constructs an HTTP POST request targeting the upload endpoint. The request body is the contents of a local text file.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `HttpRequest request = HttpRequest.newBuilder()` // Start request builder |
| 2 | EXEC | `.uri(new URI("http://localhost:8080/upload/"))` // Set target URI |
| 3 | EXEC | `.POST(HttpRequest.BodyPublishers.ofFile(Paths.get("/tmp/files-to-upload.txt")))` // Set POST body from file |
| 4 | EXEC | `.build();` // Finalize the HttpRequest object |

**Block 3** — EXEC (send request and discard body) (L112)

> Sends the request synchronously. The response body is discarded since only the status code is used.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());` // Send POST, ignore response body |

**Block 4** — EXEC (print status) (L113)

> Prints the HTTP status code of the response to standard output for verification.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `System.out.println(response.statusCode());` // Print HTTP status code |

**Block 5** — RETURN (implicit) (L114)

| # | Type | Code |
|---|------|------|
| 1 | RETURN | Implicit `return;` // Method returns void |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `uploadFile` | Method | File upload — sends the contents of a local file to a remote HTTP server via POST |
| HttpClient | JDK API | Java 11 built-in HTTP client (`java.net.http.HttpClient`) for sending HTTP requests synchronously or asynchronously |
| HttpRequest | JDK API | Java 11 HTTP request object, built via a fluent builder pattern. Can carry a body from a string, byte array, or file |
| HttpResponse | JDK API | Java 11 HTTP response object containing status code, headers, and a body accessible via BodyHandlers |
| BodyHandlers.discarding() | JDK API | Response handler that discards the response body, used when only metadata (status code, headers) is needed |
| BodyPublishers.ofFile() | JDK API | Request body publisher that reads file contents from a local `Path`, setting the request body to the file's bytes |
| localhost:8080 | Target | Local development server endpoint for file upload (hardcoded) |
| /tmp/files-to-upload.txt | File path | Local filesystem path of the file to upload (hardcoded) |
