HTTP (Hypertext Transfer Protocol)

HTTP is an application-layer protocol centered on request and response semantics, where method, target, header fields, status code, and content together express an interaction. HTTP/1.1, HTTP/2, and HTTP/3 preserve these core semantics while differing in message encoding and underlying transport.

Second-Draft Verification Note (2026-10-15): This is the second draft of the HeLuoXu tutorial, revised against official specifications and documentation. Legacy experiment logs are labeled separately as "First-Draft Retained Output" and do not represent a re-run on Windows in this pass; see the current batch verification records for the environment and results of this pass. Examples such as "StarRiver Notes", accounts, orders, prices, and policies are fictional teaching data.

One-Sentence Definition

HTTP is an application-layer protocol centered on request and response semantics, where method, target, header fields, status code, and content together express an interaction. HTTP/1.1, HTTP/2, and HTTP/3 preserve these core semantics while differing in message encoding and underlying transport.

Why It Matters

  • Web frameworks handle HTTP interactions while adding routing, data validation, and rendering; understanding raw HTTP messages is essential for diagnosing 401, 413, 429, 502, and 504 errors.
  • LLM API streaming responses, rate limiting (429 + Retry-After), and timeouts all operate directly at the HTTP layer.
  • Caching (ETag, Cache-Control), compression, and persistent connections directly shape service latency and bandwidth costs.

How It Works / Diagram

HTTP Semantics: RFC 9110 https://www.rfc-editor.org/rfc/rfc9110; HTTP/1.1 Message Syntax: RFC 9112 https://www.rfc-editor.org/rfc/rfc9112; HTTP/2: RFC 9113; HTTP/3: RFC 9114; MDN HTTP Guide: https://developer.mozilla.org/zh-CN/docs/Web/HTTP

Figure 1
Status Code Class Meaning Common Examples
2xx Success Request was successfully received and processed 200 OK, 201 Created, 204 No Content
3xx Redirection / Cache Fetch from another URI or use cached representation 301, 302, 304 Not Modified
4xx Client Error Problem with the client's request 400, 401 Unauthenticated, 403 Forbidden, 404, 409 Conflict, 422 Validation Failed, 429 Too Many Requests
5xx Server Error Failure on the server or upstream side 500, 501 Not Implemented, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout
Version Transport Key Improvements
HTTP/1.1 TCP, text-delimited messages Persistent connections, chunked transfer coding
HTTP/2 TCP, binary frames Multiplexed streams over a single connection, header compression (HPACK)
HTTP/3 QUIC (over UDP) Mitigates transport-layer head-of-line blocking, supports connection migration

Applicable Boundaries & Verification Points

Text request lines and chunked transfer coding belong specifically to HTTP/1.1 wire syntax; HTTP/2 and HTTP/3 use binary framing and do not support chunked transfer encoding. HTTP/3 runs over QUIC, where TLS 1.3 is integrated into the transport handshake. A single TCP recv() call boundary does not correspond to an HTTP message boundary or an SSE event boundary—clients must loop until they have read the full header block plus the body length specified by Content-Length, chunked framing, or connection closure. Calling GET a "safe" method means the client does not request any state change on the origin server, not that the server is forbidden from writing access logs. Automated retries must account for method idempotency, server contracts, overall retry budgets, and retry storms.

Primary references verified in this pass (2026-10-15):

  • RFC 9110: HTTP Semantics: safe and idempotent methods, conditional requests, and status codes.
  • RFC 9113: HTTP/2: prohibition of HTTP/1.1 connection-specific header fields and chunked transfer coding.

Runnable Example

This Python standard-library server listens only on the local loopback address. The second-draft client reads in a loop according to response header delimiters, Content-Length, or chunked boundaries to inspect raw HTTP/1.1 bytes; it is a teaching reader rather than a general-purpose HTTP client covering every edge case.

# File: examples/09_http.py
"""Inspect raw HTTP/1.1 wire messages over a socket: request line, headers, status codes, keep-alive, conditional requests, and chunked transfer."""
import socket, threading, hashlib, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

DOC = "StarRiver Notes Help: 7-day no-questions-asked refund.\n".encode()
ETAG = '"' + hashlib.sha256(DOC).hexdigest()[:16] + '"'
class H(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"                # Enable persistent connections
    def log_message(self, *a): pass
    def do_GET(self):
        if self.path == "/help":
            if self.headers.get("If-None-Match") == ETAG:          # Conditional request: content unchanged
                self.send_response(304); self.send_header("ETag", ETAG); self.end_headers(); return
            self.send_response(200)
            self.send_header("Content-Type", "text/plain; charset=utf-8")
            self.send_header("Content-Length", str(len(DOC))); self.send_header("ETag", ETAG)
            self.end_headers(); self.wfile.write(DOC)
        elif self.path == "/stream":                                  # Chunked transfer: send chunks as they are generated
            self.send_response(200); self.send_header("Content-Type", "text/plain; charset=utf-8")
            self.send_header("Transfer-Encoding", "chunked"); self.end_headers()
            for tok in ["Hello", ", ", "I am ", "support"]:
                b = tok.encode(); self.wfile.write(f"{len(b):x}\r\n".encode() + b + b"\r\n"); self.wfile.flush(); time.sleep(0.05)
            self.wfile.write(b"0\r\n\r\n")
        else:
            body = b'{"error":"not found"}'
            self.send_response(404); self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)

srv = ThreadingHTTPServer(("127.0.0.1", 0), H); port = srv.server_address[1]
threading.Thread(target=srv.serve_forever, daemon=True).start()

def show(raw: bytes, label):
    head, _, body = raw.partition(b"\r\n\r\n")
    print(f"--- {label}"); print(head.decode().replace("\r\n", "\n"))
    if body: print("[body]", body)

s = socket.create_connection(("127.0.0.1", port)); s.settimeout(2)
pending = bytearray()
def take_until(marker):
    while marker not in pending:
        part = s.recv(4096)
        if not part: raise EOFError("Connection closed before message boundary")
        pending.extend(part)
    end = pending.index(marker) + len(marker)
    result = bytes(pending[:end]); del pending[:end]
    return result
def take_n(n):
    while len(pending) < n:
        part = s.recv(4096)
        if not part: raise EOFError("Incomplete response body")
        pending.extend(part)
    result = bytes(pending[:n]); del pending[:n]
    return result
def receive_response():
    head = take_until(b"\r\n\r\n")
    lines = head.decode("iso-8859-1").split("\r\n")
    status = int(lines[0].split()[1])
    headers = dict((k.lower(), v.strip()) for k, v in (line.split(":", 1) for line in lines[1:] if line))
    body = b""
    if status in (204, 304) or 100 <= status < 200: return head
    if headers.get("transfer-encoding", "").lower() == "chunked":
        while True:
            size_line = take_until(b"\r\n"); body += size_line
            size = int(size_line.split(b";", 1)[0], 16)
            if size == 0:
                while True:
                    trailer = take_until(b"\r\n"); body += trailer
                    if trailer == b"\r\n": return head + body
            block = take_n(size + 2)
            if not block.endswith(b"\r\n"): raise ValueError("Invalid chunk terminator")
            body += block
    if "content-length" not in headers: raise ValueError("This teaching client only handles Content-Length or chunked responses")
    return head + take_n(int(headers["content-length"]))
def send(req: str, label):
    s.sendall(req.encode()); data = receive_response(); show(data, label); return data

print("1. A request message is just a few lines of text:")
req = f"GET /help HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nUser-Agent: k6-demo\r\nAccept: text/plain\r\n\r\n"
print(repr(req))
r1 = send(req, "2. Response 200 (note that Content-Length is counted in bytes)")
print("UTF-8 text character count:", len(DOC.decode()), ", byte count:", len(DOC))
send(f"GET /help HTTP/1.1\r\nHost: x\r\nIf-None-Match: {ETAG}\r\n\r\n", "3. Second request over the same TCP connection: with If-None-Match -> 304, no body")
send("GET /nope HTTP/1.1\r\nHost: x\r\n\r\n", "4. Non-existent path -> 404")
s.sendall(b"GET /stream HTTP/1.1\r\nHost: x\r\n\r\n")
t0 = time.perf_counter()
buf = receive_response()
show(buf, "5. Chunked transfer (this client reads by HTTP framing rather than assuming a single recv gets everything)")
print("Total stream receive duration (ms, not per-chunk arrival timestamps):", round((time.perf_counter() - t0) * 1000))
s.sendall(b"BREW /coffee HTTP/1.1\r\nHost: x\r\n\r\n")
print("--- 6. Unimplemented method\n" + receive_response().decode().split("\r\n")[0])
s.close(); srv.shutdown(); srv.server_close()

First-Draft Retained Output

The following log is retained from the first draft and reflects the original environment claimed there; it is not the re-run output of this pass. Second-draft code edits may produce different output; refer to the current batch verification records for the actual re-run status.

1. A request message is just a few lines of text:
'GET /help HTTP/1.1\r\nHost: 127.0.0.1:34691\r\nUser-Agent: k6-demo\r\nAccept: text/plain\r\n\r\n'
--- 2. Response 200 (note that Content-Length is counted in bytes)
HTTP/1.1 200 OK
Server: BaseHTTP/0.6 Python/3.12.15
Date: Wed, 14 Oct 2026 13:43:33 GMT
Content-Type: text/plain; charset=utf-8
Content-Length: 51
ETag: "76b90d86b0742cc0"
[body] b'\xe6\x98\x9f\xe6\xb2\xb3\xe7\xac\x94\xe8\xae\xb0\xe5\xb8\xae\xe5\x8a\xa9\xef\xbc\x9a7 \xe5\xa4\xa9\xe5\x86\x85\xe5\x8f\xaf\xe6\x97\xa0\xe7\x90\x86\xe7\x94\xb1\xe9\x80\x80\xe6\xac\xbe\xe3\x80\x82\n'
UTF-8 text character count: 19 , byte count: 51
--- 3. Second request over the same TCP connection: with If-None-Match -> 304, no body
HTTP/1.1 304 Not Modified
Server: BaseHTTP/0.6 Python/3.12.15
Date: Wed, 14 Oct 2026 13:43:34 GMT
ETag: "76b90d86b0742cc0"
--- 4. Non-existent path -> 404
HTTP/1.1 404 Not Found
Server: BaseHTTP/0.6 Python/3.12.15
Date: Wed, 14 Oct 2026 13:43:34 GMT
Content-Type: application/json
Content-Length: 21
[body] b'{"error":"not found"}'
--- 5. Chunked transfer (one underlying transport form for LLM streaming output)
HTTP/1.1 200 OK
Server: BaseHTTP/0.6 Python/3.12.15
Date: Wed, 14 Oct 2026 13:43:34 GMT
Content-Type: text/plain; charset=utf-8
Transfer-Encoding: chunked
[body] b'6\r\n\xe4\xbd\xa0\xe5\xa5\xbd\r\n3\r\n\xef\xbc\x8c\r\n6\r\n\xe6\x88\x91\xe6\x98\xaf\r\n6\r\n\xe5\xae\xa2\xe6\x9c\x8d\r\n0\r\n\r\n'
Chunk arrival timestamps (ms, approximate): [0, 50, 100, 150, 201]
--- 6. Unimplemented method
HTTP/1.1 501 Unsupported method ('BREW')
  • 1. An HTTP/1.1 request is simply text lines delimited by \r\n and terminated by an empty line (\r\n\r\n); the Host header is mandatory in HTTP/1.1.
  • 2. Content-Length: 51 measures bytes: in the original UTF-8 payload of 19 characters, each common CJK character took 3 bytes (other Unicode code points vary), totaling 51 bytes. If a custom server sets Content-Length to the character count instead of the byte length, clients will either truncate the response or hang waiting for bytes.
  • 3. The second request reuses the exact same TCP connection (HTTP/1.1 enables keep-alive by default). When the client sends If-None-Match with the cached ETag, the server sees the resource is unchanged and replies 304 Not Modified with no body—browsers and CDNs rely on this to save bandwidth.
  • 4. The 404 response returns a JSON body: the HTTP status code signals the category of outcome, while the body carries structured details.
  • 5. Chunked transfer encoding formats each chunk as "hexadecimal byte length + CRLF + data + CRLF" (in the retained log, 6 meant 6 UTF-8 bytes for two CJK characters) and terminates with a 0-length chunk. In the first-draft localhost test, chunks arrived roughly every 50 ms, whereas real networks may coalesce or split TCP segments arbitrarily. Over HTTP/1.1, streaming LLM API responses typically run as Server-Sent Events (text/event-stream) carried inside chunked encoding; HTTP/2 forbids Transfer-Encoding: chunked and splits payloads across binary DATA frames instead (RFC 9113 Section 8.2.2: https://www.rfc-editor.org/rfc/rfc9113#section-8.2.2).
  • 6. An unrecognized HTTP method such as BREW returns 501 Not Implemented.

Self-Test

Question: If a single recv() call returns only half of a JSON response, does that mean the server sent corrupted data?

Reference Answer: Not necessarily. TCP is a byte stream, so a single read call can return any arbitrary slice of bytes. The client must buffer bytes until the HTTP message framing is complete before parsing the payload—and for SSE streams, it must also accumulate bytes across network reads until complete event delimiters arrive.

Common Misconceptions

  • "HTTPS is a completely different application protocol": HTTPS is HTTP running over a TLS-encrypted connection; the HTTP request and response semantics remain identical.
  • "401 and 403 mean the same thing": 401 Unauthorized indicates that valid authentication credentials are missing or rejected, whereas 403 Forbidden means the server understood the request but refuses to authorize it; 403 does not require that a user identity was lacking (see k6.sec.authentication and k6.sec.authorization).
  • "It is fine to mutate database state in a GET request": RFC 9110 defines GET as a safe method whose purpose must not be to mutate application state (incidental server side effects like access logging are allowed); crawlers, browser prefetchers, and caches freely issue and replay GET requests.
  • "If a POST fails, just retry it blindly": POST is not idempotent by default, so blind retries can create duplicate orders or charges; use an idempotency key when retrying mutating requests (see k6.web.rest-api).

Connection to AI Development

  • When an LLM API returns 429, inspect the Retry-After header and retry with exponential backoff; on 5xx errors, retry a bounded number of times; for other 4xx responses, handle the specific error semantics (for example, refreshing state on a 409 conflict) rather than retrying the identical request indefinitely.
  • When streaming responses pass through a reverse proxy (such as Nginx), default proxy buffering can hold back chunks until the response finishes, turning a live stream into a single delayed dump; disable proxy buffering for streaming endpoints (Nginx proxy_buffering: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering).
  • curl -v prints the full request and response headers and is one of the quickest tools for debugging API calls.

Further Reading

Unverified Scope

  • This script covers only a subset of HTTP/1.1 responses and is not a full RFC-compliant HTTP parser; it does not test HTTP/2, HTTP/3, or production reverse-proxy pipelines.

Current Example Execution Scope

2026-10-15: Passed. Local loopback HTTP/1.1 response reader with bounded message framing.

View current execution log.

"First-Draft Retained Output" preserves the original text and is not newly generated by the second-draft code; its original conclusions must be read together with the second-draft revisions and boundary notes.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram