Sub topic 13
HTTP messages: request line, headers, and body
HTTP is a text-based request and response protocol that runs on top of a reliable byte stream, normally TCP. This chapter assumes you know what a socket is, how a TCP connection is opened, and how a DNS lookup produces an IP address. It covers the structure of HTTP/1.1 messages, how a receiver finds where a message ends, and the mistakes that most often appear in exam questions.
Where HTTP fits
HTTP is an application-layer protocol. A client (usually a browser) opens a TCP connection to a server, sends a request message, and reads a response message. The server does not start the conversation. The default port is 80 for HTTP and 443 for HTTP over TLS.
Two properties shape everything else in the protocol:
- HTTP is stateless. The server treats each request on its own and keeps no memory of earlier ones. Cookies, covered in a later chapter, add state on top.
- HTTP/1.1 is a plain-text format. TCP delivers bytes without message boundaries, so HTTP must define its own rules for marking where a message begins and ends.
The shape of a message
Request and response messages share one layout:
- A start line (request line or status line).
- Zero or more header lines, each of the form
Name: value. - A blank line.
- An optional body.
Every line ends with CRLF, the two bytes carriage return (\r) and line feed (\n). The blank line is just a CRLF with nothing before it. It is the only signal that the headers are finished, so leaving it out makes the receiver wait for more headers.
The request line
The request line has three fields separated by single spaces:
GET /index.html HTTP/1.1| Field | Meaning | Example |
|---|---|---|
| Method | The action requested | `GET`, `POST` |
| Request target | The resource, usually a path and optional query | `/search?q=tcp` |
| Version | The protocol version | `HTTP/1.1` |
The target is normally a path, not a full URL, because the TCP connection already identifies the server. The server name travels in the Host header instead.
The status line
The response begins with a status line:
HTTP/1.1 200 OKIt holds the version, a three-digit status code, and a human-readable reason phrase. Programs act on the code. The phrase is only a label. Status codes are covered in the next chapter.
Headers
Each header is a name, a colon, and a value. Names are case-insensitive, so content-length and Content-Length are the same header. Values may be case-sensitive depending on the header.
HTTP/1.1 makes one request header mandatory: Host. A single IP address may serve many sites (virtual hosting). Only the Host header tells the server which site the client wants. A request without it is invalid and a compliant server answers 400 Bad Request.
Some commonly seen headers:
| Header | Direction | Purpose |
|---|---|---|
| `Host` | Request | Names the target host and optional port |
| `User-Agent` | Request | Identifies the client software |
| `Accept` | Request | Media types the client can handle |
| `Content-Type` | Both | Media type of the body, such as `text/html` |
| `Content-Length` | Both | Body size in bytes |
| `Transfer-Encoding` | Both | Framing of the body, such as `chunked` |
| `Connection` | Both | Connection options, such as `close` |
| `Server` | Response | Identifies the server software |
The body
The body carries the payload: an HTML page in a response, or form data in a POST request. Many requests, such as a typical GET, have no body. A request has a body only if the headers say so.
A complete exchange
A request carrying form data:
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 27
user=alice&password=secret1The matching response:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 13
Connection: close
Hello, Alice!In the request, Content-Length: 27 counts the bytes of user=alice&password=secret1, which is 27 characters in ASCII. The count excludes the blank line before the body.
How the receiver finds the end of a message
TCP gives a stream of bytes, so the receiver needs a rule for where one HTTP message stops. HTTP/1.1 uses these mechanisms:
- No body. If the message cannot have a body (for example a response to
HEAD, or a204or304response), it ends at the blank line. Content-Length. The receiver reads exactly that many bytes after the blank line.Transfer-Encoding: chunked. The body is sent as chunks, each preceded by its size in hexadecimal, and ends with a chunk of size zero. This lets a server start sending before it knows the total size.- Connection close. For a response with neither header, the body runs until the server closes the TCP connection. This option is only available for responses, and it prevents reusing the connection.
A chunked body looks like this:
HTTP/1.1 200 OK
Transfer-Encoding: chunked
5
Hello
7
, world
0
Sizes are hexadecimal: 5 is five bytes and 7 is seven bytes. The final 0 plus a blank line ends the body.
Seeing it from code
The following script sends a request by hand and splits the response into its parts. It makes the structure visible: the first line, the headers, the blank line, and the body.
import socket
host = "example.com"
request = (
"GET / HTTP/1.1\r\n"
f"Host: {host}\r\n"
"Connection: close\r\n"
"\r\n"
)
with socket.create_connection((host, 80)) as s:
s.sendall(request.encode("ascii"))
raw = b""
while True:
chunk = s.recv(4096)
if not chunk:
break
raw += chunk
head, _, body = raw.partition(b"\r\n\r\n")
lines = head.decode("iso-8859-1").split("\r\n")
print("Status line:", lines[0])
for line in lines[1:]:
name, _, value = line.partition(":")
print(f"Header {name.strip()!r} = {value.strip()!r}")
print("Body length so far:", len(body), "bytes")Notes on this code:
partition(b"\r\n\r\n")splits at the first blank line, which separates headers from body.Connection: closeasks the server to close after responding, so therecvloop ends when the stream ends.- If the response uses chunked encoding,
bodystill contains the chunk-size lines. A real client must decode them.
Common errors
- Forgetting the
Hostheader. HTTP/1.1 servers reject the request or return the wrong site. - Using
\ninstead of\r\n. Some servers tolerate it, but the standard requires CRLF. - Missing the final blank line. The server keeps waiting for headers and the request appears to hang.
- Wrong
Content-Length. A value too small cuts the body off, and the leftover bytes are read as the start of the next message. A value too large makes the receiver wait for bytes that never arrive. - Assuming one
recvequals one message. TCP may split a message across several reads or join several messages in one read. - Confusing the request target with the URL. The request line usually carries only the path, while the host goes in
Host.
Counting bytes in a message
Suppose a client sends this request, with every line ending in CRLF:
GET /a HTTP/1.1
Host: x.com
Count each part:
GET /a HTTP/1.1is 15 characters, plus 2 for CRLF, giving 17.Host: x.comis 11 characters, plus 2, giving 13.- The blank line adds 2.
The total is 17 + 13 + 2 = 32 bytes. This kind of count appears when a question asks how many TCP segments or how much transmission time a request needs.
Exercises
Exercise
A response has the headers Content-Type: text/html and Content-Length: 120, followed by the blank line and the body. How does the client know the message is complete, and what happens if the server sends only 100 body bytes and then keeps the connection open?
Show answer
The client reads exactly 120 bytes after the blank line. If the server sends only 100 bytes and keeps the connection open, the client keeps waiting for the remaining 20 bytes, so the response appears to hang until a timeout or until the server closes the connection.
Exercise
A chunked response body is A\r\n0123456789\r\n3\r\nabc\r\n0\r\n\r\n. How many body bytes does the client receive in total?
Show answer
The sizes are hexadecimal. A is 10 bytes and 3 is 3 bytes, and the final 0 chunk ends the body. The total is 10 + 3 = 13 bytes.
Exercise
Why is the Host header required in HTTP/1.1 even though the client has already opened a TCP connection to the server's IP address?
Show answer
One IP address and port can serve many websites. The TCP connection identifies only the IP address and port, not the site name. The Host header tells the server which site the request is for.