---
dd_id: DD02
class: Example
method: basicAuth
signature: static void basicAuth()
return_type: void
fqn: io.github.biezhi.java11.http.Example
file: src/main/java/io/github/biezhi/java11/http/Example.java
loc: 19
---

# (DD02) 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`) |
| Module | `http` (Package: `io.github.biezhi.java11.http`) |

## 1. Role

### Example.basicAuth()

This method is a standalone demonstration of HTTP Basic Authentication using Java 11's `HttpClient` API (introduced in JEP 321). It constructs an `HttpClient` instance configured with a custom `Authenticator` that automatically supplies hardcoded credentials ("username"/"password") whenever the target server requests basic authentication. It then issues an HTTP GET request to `https://labs.consol.de` and prints the response status code and body to standard output. As a convenience utility method (static, in an `Example` class), it serves as a runnable code sample for developers learning how to handle authenticated HTTP requests in Java 11 without external libraries. It implements the **delegation pattern** — the `HttpClient` delegates authentication challenge handling to the embedded `Authenticator` callback.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["basicAuth()"])
    client["HttpClient.newBuilder()"]
    auth["Configurator Authenticator"]
    build1["build() -> HttpClient instance"]
    request["HttpRequest.newBuilder()"]
    uri["uri(URI https://labs.consol.de)"]
    method["GET()"]
    build2["build() -> HttpRequest instance"]
    send["client.send(request, BodyHandlers.ofString())"]
    status["System.out.println(response.statusCode())"]
    body["System.out.println(response.body())"]
    END_NODE(["Return (void)"])

    START --> client
    client --> auth
    auth --> build1
    build1 --> request
    request --> uri
    uri --> method
    method --> build2
    build2 --> send
    send --> status
    status --> body
    body --> END_NODE
```

**Processing Flow:**

1. **Create HttpClient** — A builder is invoked on `HttpClient` to start configuration, and an `Authenticator` is provided as a lambda/anonymized class override that returns a `PasswordAuthentication` with credentials `"username"` / `"password"`. The builder is then `build()`-ed into a concrete `HttpClient` instance.

2. **Create HttpRequest** — A separate builder is invoked on `HttpRequest` to start configuration. The URI is set to `https://labs.consol.de` via `new URI(...)`. The HTTP method is set to `GET` via `.GET()`. The request is then `build()`-ed into a concrete `HttpRequest` instance.

3. **Send Request** — The configured `HttpClient` sends the request using `client.send(request, HttpResponse.BodyHandlers.ofString())`. This is a blocking call that waits for the full HTTP response, with the body decoded as a `String`.

4. **Process Response** — The response's HTTP status code and body are printed to `System.out`.

5. **Return** — Method returns `void`.

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| - | (none) | - | This method takes no parameters. All configuration (credentials, URI, HTTP method) is hardcoded inline. |

**External State:**
| Source | Description |
|--------|-------------|
| `HttpClient` (JDK `java.net.http`) | Java 11 standard library HTTP client; provides synchronous, blocking, non-streaming HTTP calls |
| `Authenticator` (JDK `java.net.Authenticator`) | Java standard library callback for supplying credentials when the server sends a 401 challenge; the embedded anonymous class returns `PasswordAuthentication("username", "password".toCharArray())` |
| `HttpRequest` (JDK `java.net.http`) | Java 11 standard library HTTP request builder; used to construct the GET request targeting `https://labs.consol.de` |
| `HttpResponse` (JDK `java.net.http`) | Java 11 standard library HTTP response container; provides `statusCode()` and `body()` accessors |

## 4. CRUD Operations / Called Services

This method does **not** call any application-level service, CBS, or SC methods. All operations use the Java 11 standard library (`java.net.http`).

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| *(none)* | *(none)* | *(none)* | *(none)* | This method is a self-contained HTTP client demo; no enterprise service layer, database, or business service component is involved. |

**API Calls:**

| Type | Target | Description |
|------|--------|-------------|
| HTTP GET | `https://labs.consol.de` | Sends a basic-authenticated GET request; the embedded `Authenticator` supplies credentials on 401 challenge |

## 5. Dependency Trace

**Callers of `Example.basicAuth()`:**

No callers found in the codebase. This method is a static utility used only as a standalone runnable example.

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

**Methods Called By `Example.basicAuth()`:**

| # | Called Method | Category | Description |
|---|--------------|----------|-------------|
| 1 | `HttpClient.newBuilder()` | JDK API | Creates an `HttpClient.Builder` for configuring the HTTP client |
| 2 | `HttpClient.Builder.authenticator()` | JDK API | Registers the embedded `Authenticator` callback for credential supply |
| 3 | `HttpClient.Builder.build()` | JDK API | Produces a configured `HttpClient` instance |
| 4 | `HttpRequest.newBuilder()` | JDK API | Creates an `HttpRequest.Builder` for constructing the request |
| 5 | `HttpRequest.Builder.uri()` | JDK API | Sets the target URI to `https://labs.consol.de` |
| 6 | `HttpRequest.Builder.GET()` | JDK API | Sets the HTTP method to GET |
| 7 | `HttpRequest.Builder.build()` | JDK API | Produces a configured `HttpRequest` instance |
| 8 | `HttpClient.send()` | JDK API | Sends the request synchronously and returns the `HttpResponse` |
| 9 | `HttpResponse.BodyHandlers.ofString()` | JDK API | Configures body handling to decode the response as a String |
| 10 | `HttpResponse.statusCode()` | JDK API | Returns the HTTP status code (e.g., 200, 401) |
| 11 | `HttpResponse.body()` | JDK API | Returns the response body as a decoded String |
| 12 | `System.out.println()` | JDK API | Prints status code and body to standard output |

## 6. Per-Branch Detail Blocks

This method has **no conditional branches** (no if/else, no switch, no loops, no try-catch). The control flow is entirely linear.

### Block 1 — HTTP Client Construction (L134–L141)

> Configures and builds an `HttpClient` with an embedded `Authenticator` that returns hardcoded credentials.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `HttpClient.newBuilder()` | Create an `HttpClient.Builder` instance |
| 2 | EXEC | `.authenticator(new Authenticator() { ... })` | Attach an anonymous `Authenticator` class that overrides `getPasswordAuthentication()` to return `PasswordAuthentication("username", "password".toCharArray())` |
| 3 | EXEC | `.build()` | Build a configured `HttpClient` instance; assigned to local variable `client` |

### Block 2 — HTTP Request Construction (L143–L147)

> Configures and builds an `HttpRequest` targeting `https://labs.consol.de` with the GET method.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `HttpRequest.newBuilder()` | Create an `HttpRequest.Builder` instance |
| 2 | EXEC | `.uri(new URI("https://labs.consol.de"))` | Set the target URI; hard-coded value |
| 3 | EXEC | `.GET()` | Set HTTP method to GET |
| 4 | EXEC | `.build()` | Build a configured `HttpRequest` instance; assigned to local variable `request` |

### Block 3 — Request Execution and Response Handling (L149–L151)

> Sends the request synchronously, then prints the status code and body.

| # | Type | Code |
|---|------|------|
| 1 | CALL | `client.send(request, HttpResponse.BodyHandlers.ofString())` | Blocking HTTP call; returns `HttpResponse<String>` assigned to `response` |
| 2 | EXEC | `System.out.println(response.statusCode())` | Print the HTTP status code |
| 3 | EXEC | `System.out.println(response.body())` | Print the response body as a string |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `basicAuth` | Method | HTTP Basic Authentication — a standard HTTP authentication scheme where credentials are base64-encoded and sent in the `Authorization` header |
| `HttpClient` | JDK Class | Java 11 standard library class for sending HTTP requests; introduced by JEP 321 as the modern replacement for `HttpURLConnection` |
| `HttpRequest` | JDK Class | Java 11 standard library class representing a configured HTTP request (method, URI, headers, body) |
| `HttpResponse` | JDK Class | Java 11 standard library class containing the server's HTTP response (status code, headers, body) |
| `Authenticator` | JDK Class | Java standard library class (`java.net.Authenticator`) that supplies credentials (username/password) when the HTTP server returns a 401 Unauthorized challenge |
| `PasswordAuthentication` | JDK Class | Java class holding a username and password character array returned by `Authenticator.getPasswordAuthentication()` |
| `BodyHandlers.ofString()` | JDK API | A response body handler that decodes the HTTP response body as a UTF-8 `String` |
| `https://labs.consol.de` | URI | Target server URL for this HTTP request (a demonstration endpoint maintained by Consol Labs) |
| `newBuilder()` | Pattern | Builder factory method returning a mutable builder instance for fluent configuration |
| `build()` | Pattern | Builder terminal method that produces an immutable, configured instance |
