Sub topic 13
HTTP Messages: Request Line, Headers, and Body
This chapter assumes that you know the layered network model, TCP provides a byte stream, and a client can identify a server using an IP address and port. HTTP is an application-layer protocol that defines how a client and server represent requests and responses.
The structure of an HTTP message
An HTTP message has three logical parts:
- A start line.
- Zero or more headers.
- An optional body.
The start line and each header line end with a carriage return and line feed, written as CRLF. An empty CRLF line separates the headers from the body.
A request starts with a request line:
method target versionFor example:
GET /index.html HTTP/1.1The method describes the desired operation. The target identifies the resource. The version identifies the HTTP rules being used.
A response starts with a status line:
version status-code reason-phraseFor example:
HTTP/1.1 200 OKThe status code tells the client whether the request succeeded and what happened.
Headers and the body
A header is a name and value separated by a colon. Headers carry metadata about the message, the selected resource, the client, or the connection.
Host: example.com
Accept: text/html
Content-Type: application/json
Content-Length: 18The Host header identifies the destination hostname. It is required in HTTP/1.1 requests because many hostnames can share one IP address.
Content-Type describes the format of the body. Content-Length gives the body size in bytes. The server uses this information to determine where the message body ends. A response can also use chunked transfer encoding instead of Content-Length.
The body carries data such as an HTML document, JSON object, uploaded file, or form data. A GET request commonly has no body, while a POST request often includes one.
Worked example
The following program separates a raw HTTP request into its request line, headers, and body. It uses split with a limit of one so that any additional blank-line-like text remains part of the body.
raw_request = (
"POST /login HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Type: application/json\r\n"
"Content-Length: 27\r\n"
"\r\n"
'{"user":"ana","ok":true}'
)
header_part, body = raw_request.split("\r\n\r\n", 1)
lines = header_part.split("\r\n")
request_line = lines[0]
headers = {}
for line in lines[1:]:
name, value = line.split(":", 1)
headers[name.strip()] = value.strip()
print("Request line:", request_line)
print("Headers:", headers)
print("Body:", body)The blank line is a protocol delimiter. It is not merely visual formatting. Without it, the receiver cannot reliably tell where the headers finish.
Exercise
A response contains Content-Length: 12 and then 12 body bytes. Does the Content-Length include the status line and headers?
Show answer
No. Content-Length counts only the response body, in bytes. The status line, headers, and separating blank line are not included.