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

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

## 1. Role

### Example.basicAuth()

This method demonstrates how to perform HTTP Basic Authentication when making HTTP requests using the Java 11 `HttpClient` API (introduced in JDK 11 as part of JEP 110 and JEP 321). It serves as a self-contained example for developers learning or referencing the correct pattern for configuring an authenticator on an `HttpClient`. The method creates an `HttpClient` instance with an embedded `Authenticator` that supplies hardcoded credentials (`username` / `password`), constructs a `HttpRequest` to fetch the homepage at `https://labs.consol.de` using the `GET` method, sends the request synchronously, and prints the HTTP status code and response body to standard output. In the larger system (the java11-http-client demo project by biezhi), this method is a standalone educational entry point — a "cookbook" example — not a shared utility called by other code. It implements the builder pattern via `HttpClient.newBuilder()` and `HttpRequest.newBuilder()`, and follows the delegation pattern by creating an anonymous inner `Authenticator` subclass whose `getPasswordAuthentication()` method is invoked by the `HttpClient` whenever the remote server challenges with a `401 Unauthorized` response.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["basicAuth()"])
    STEP1["Create HttpClient with Authenticator"]
    STEP2["Build HttpClient"]
    STEP3["Create HttpRequest with URI https://labs.consol.de"]
    STEP4["Set HTTP method to GET"]
    STEP5["Build HttpRequest"]
    STEP6["Send request synchronously with BodyHandlers.ofString()"]
    STEP7["Print response status code"]
    STEP8["Print response body"]
    END_NODE(["Method ends"])

    START --> STEP1
    STEP1 --> STEP2
    STEP2 --> STEP3
    STEP3 --> STEP4
    STEP4 --> STEP5
    STEP5 --> STEP6
    STEP6 --> STEP7
    STEP7 --> STEP8
    STEP8 --> END_NODE
```

**Processing Description:**

The method follows a linear (sequential, no branches) flow:

1. **HttpClient Creation with Authenticator (L134–L142):** A `HttpClient` is built via the builder pattern. An anonymous `Authenticator` subclass is passed to `.authenticator()`. When the remote server responds with HTTP `401 Unauthorized`, the `HttpClient` automatically invokes the overridden `getPasswordAuthentication()` method of this `Authenticator`, which returns a `PasswordAuthentication` object containing the credentials `"username"` / `"password"`. The `HttpClient` then re-transmits the request with the `Authorization: Basic <base64-encoded-credentials>` header.

2. **HttpRequest Construction (L144–L147):** A `HttpRequest` is built via the builder pattern. The URI is set to `https://labs.consol.de`, the HTTP method is set to `GET`, and the request object is finalized.

3. **Synchronous Request Execution (L149):** The `HttpClient.send()` method is called, which performs a synchronous (blocking) HTTP request. The response body is handled via `HttpResponse.BodyHandlers.ofString()`, which collects the full response body into a `String`.

4. **Response Output (L150–L151):** The HTTP status code (`statusCode()`) and response body (`body()`) are printed to `System.out`.

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| - | (none) | - | This is a static method with no parameters. It uses hardcoded values throughout. |

**External state / instance fields accessed:** None. The method is fully self-contained and stateless.

| Source | Description |
|--------|-------------|
| `"username"` | Hardcoded basic auth username (string literal) |
| `"password"` | Hardcoded basic auth password (string literal) |
| `"https://labs.consol.de"` | Target HTTP(S) endpoint URI |
| `System.out` | Standard output stream used to print results |

## 4. CRUD Operations / Called Services

This method does **not** perform any database or service component (SC/CBS) operations. It is a pure HTTP client demonstration that makes a single outbound HTTP `GET` request.

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| — | — | — | — | No SC/CBS or database operations. This method makes an outbound HTTP request to `https://labs.consol.de` using the Java 11 `HttpClient` API. |

**External HTTP call:**

| # | Target | HTTP Method | Description |
|---|--------|-------------|-------------|
| 1 | `https://labs.consol.de` | GET | Fetches the homepage of the demonstrator's site. The `HttpClient` will transparently handle HTTP Basic Authentication (401 → re-send with `Authorization` header) using the embedded `Authenticator`. |

## 5. Dependency Trace

This method is a standalone example/demo method with no callers within the codebase. It serves as an educational entry point in the java11-http-client demonstration project.

| # | Caller (Screen/Batch) | Call Chain (Full Path to this Method) | Terminal (SC / CRUD / Entity) |
|---|----------------------|--------------------------------------|-------------------------------|
| 1 | N/A (standalone example) | — | No internal callers found. Called directly by developers or documentation references. |

**Reverse dependency (what this method calls):**

| # | Called Method | Type | Description |
|---|---------------|------|-------------|
| 1 | `HttpClient.newBuilder()` | JDK API | Creates a new `HttpClient.Builder` |
| 2 | `HttpClientBuilder.authenticator(Authenticator)` | JDK API | Configures the authenticator for auto-retry on 401 |
| 3 | `HttpClientBuilder.build()` | JDK API | Builds the `HttpClient` instance |
| 4 | `HttpRequest.newBuilder()` | JDK API | Creates a new `HttpRequest.Builder` |
| 5 | `HttpRequestBuilder.uri(URI)` | JDK API | Sets the target URI |
| 6 | `HttpRequestBuilder.GET()` | JDK API | Sets the HTTP method to GET |
| 7 | `HttpRequestBuilder.build()` | JDK API | Builds the `HttpRequest` instance |
| 8 | `HttpClient.send(HttpRequest, BodyHandler)` | JDK API | Synchronously sends the request and returns a response |
| 9 | `HttpResponse.statusCode()` | JDK API | Extracts the HTTP status code from the response |
| 10 | `HttpResponse.body()` | JDK API | Extracts the response body as a String |
| 11 | `System.out.println(Object)` | JDK API | Prints to standard output |

## 6. Per-Branch Detail Blocks

This method has **no conditional branches** (no if/else, no switch/case, no loops). It is a purely linear sequence. Each processing step is documented below.

**Block 1** — [LINEAR EXECUTION] (L134–L151)

> Creates an authenticated HttpClient and sends a GET request to https://labs.consol.de

| # | Type | Code |
|---|------|------|
| 1 | SET | `HttpClient client = HttpClient.newBuilder().authenticator(new Authenticator() { ... }).build();` // L134-142 — Builder chain creates an HttpClient with embedded Basic Auth credentials |
| 1.1 | EXEC | `return new PasswordAuthentication("username", "password".toCharArray());` // L138 — Returns hardcoded credentials when challenged by the server |
| 2 | SET | `HttpRequest request = HttpRequest.newBuilder().uri(new URI("https://labs.consol.de")).GET().build();` // L144-147 — Builder chain creates a GET request to the target URI |
| 3 | SET | `HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());` // L149 — Synchronous blocking send; body is collected as a String |
| 4 | EXEC | `System.out.println(response.statusCode());` // L150 — Prints the HTTP status code (e.g., 200, 401, etc.) |
| 5 | EXEC | `System.out.println(response.body());` // L151 — Prints the response body (HTML/text content from the target site) |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `HttpClient` | JDK API Class | Java 11 HTTP Client — the new standard HTTP/1.1 and HTTP/2 client introduced in JDK 11 (JEP 321) |
| `HttpRequest` | JDK API Class | Represents a single HTTP request with method, URI, and headers |
| `HttpResponse` | JDK API Class | Represents the HTTP response including status code, headers, and body |
| `Authenticator` | JDK API Class | `java.net.Authenticator` — a callback mechanism that supplies credentials (username/password) when the server requests authentication |
| `PasswordAuthentication` | JDK API Class | Holds a username and password for authentication; used by `Authenticator.getPasswordAuthentication()` |
| `Basic Auth` | Authentication scheme | HTTP Basic Authentication — the server responds with `401 Unauthorized`; the client re-sends the request with an `Authorization: Basic <base64(username:password)>` header |
| `HttpClient.newBuilder()` | JDK API Method | Factory method that returns a builder for configuring and creating `HttpClient` instances |
| `HttpRequest.newBuilder()` | JDK API Method | Factory method that returns a builder for configuring and creating `HttpRequest` instances |
| `GET` | HTTP method | HTTP GET — a method that requests a representation of the specified resource; no request body is sent |
| `BodyHandlers.ofString()` | JDK API Method | A response body handler that collects the entire response body into a single `String` |
| `401 Unauthorized` | HTTP status code | Standard HTTP response indicating the request requires valid authentication credentials |
| `Authorization` | HTTP header | Standard HTTP header carrying authentication credentials (`Basic <base64-encoded-username:password>`) |
| `labs.consol.de` | External URL | The demonstrator's website targeted by this example; used as a real-world test endpoint |

---
