Sub topic 8
Sending the HTTP request and reading the response
This chapter assumes you know what the earlier stages produce. By now the browser has resolved the host name to an IP address, opened a TCP connection, and, for https, finished the TLS handshake. You should also be comfortable reading a URL and running commands in a terminal. Here you look at the messages the browser and server exchange over that connection.
HTTP is text on a byte stream
HTTP/1.1 is a text protocol. The browser writes a request as lines of ASCII text into the connection. The server reads those lines and writes a response back. TCP only delivers an ordered stream of bytes, so HTTP defines where a message starts and ends. Every message has the same layout:
- A start line.
- Zero or more header lines, each in the form
Name: value. - An empty line.
- An optional body.
Lines end with the two bytes CRLF (\r\n). The empty line is the only signal that the headers are finished, so a missing one makes the server wait for more data.
HTTP/2 and HTTP/3 encode the same ideas in a binary format. Their messages still have methods, paths, status codes, headers and bodies. A later chapter compares the versions. The text form is the easiest one to read, so this chapter uses it.
The request
For the URL https://example.com/docs/intro?lang=en, the browser sends something like this:
GET /docs/intro?lang=en HTTP/1.1
Host: example.com
Accept: text/html
User-Agent: example-client
Connection: keep-aliveThe request line
The first line has three parts separated by single spaces.
- Method.
GETasks for a representation of the resource. Other common methods areHEAD(headers only),POST(send data for processing),PUT,DELETEandOPTIONS. - Request target. This is the path plus the query string. The scheme, host and fragment are not included. The browser keeps the fragment (
#setup) for itself and never sends it. - Protocol version.
HTTP/1.1here.
The Host header
Host is the one header HTTP/1.1 requires. A single IP address and port can serve many sites, so the request line alone does not say which site you want. A server that gets an HTTP/1.1 request without Host should answer 400 Bad Request. The TCP connection already knows the IP address, so the Host header is the only place the site name appears in the request. TLS has a similar hint called SNI, sent earlier in the handshake.
Other headers
The browser adds many headers on its own. The most common ones are listed below.
| Header | Purpose |
|---|---|
| `Accept` | Content types the client prefers |
| `Accept-Encoding` | Compression the client can decode, such as `gzip` or `br` |
| `Accept-Language` | Preferred languages |
| `User-Agent` | Identifies the client software |
| `Cookie` | Cookies previously stored for this site |
| `Connection` | Whether to keep the connection open for reuse |
Cookies are the main way a server recognizes a returning user. The browser attaches the cookies that match the request's domain, path and scheme, so a request can be much larger than the example above.
A GET request normally has no body. A POST request carries one, and it must describe it with Content-Type and Content-Length (or chunked encoding, described below).
The response
The server answers with a status line, headers, an empty line and a body:
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Cache-Control: max-age=3600
Content-Length: 1256
<!doctype html>
<html>...</html>The status line
The status line has the protocol version, a three-digit status code and a reason phrase. The reason phrase is only for humans, and clients should not depend on it. The first digit gives the class of result:
2xx: success.3xx: the client should look elsewhere or use a cached copy.4xx: the request has a problem.5xx: the server failed.
The next chapter covers individual codes and redirects.
Headers that tell the browser what to do with the body
Content-Typenames the media type and sometimes the character encoding. The browser uses it to choose a handler.text/htmlgoes to the HTML parser,text/cssto the style system,image/pngto the image decoder. If the charset is missing or wrong, text can display as garbled characters.Content-Encodingsays the body was compressed, for examplegzip. The browser decompresses it before parsing.Content-Lengththen counts the compressed bytes, not the decoded ones.Cache-Controltells the browser how long it may reuse the response. A later chapter covers it.Set-Cookieasks the browser to store a cookie and send it back on later requests.
How the browser knows the body has ended
On a connection that stays open, the browser must know where one response ends so it can reuse the connection. There are three ways:
Content-Length: Nmeans exactly N bytes of body follow.Transfer-Encoding: chunkedmeans the body arrives in pieces. Each piece starts with its size in hexadecimal, and a piece of size0ends the body. The server uses this when it starts sending before it knows the total size.- Connection close. The server closes the connection to mark the end. This is the fallback, and it prevents reuse.
A wrong Content-Length is a classic bug. If it is too small, the browser stops early and treats the leftover bytes as the start of the next response. If it is too large, the browser waits until it times out.
One exchange on the wire
The diagram below shows a single request and response on an already secured connection.
The browser can begin parsing as soon as the first body bytes arrive. It does not wait for the whole response, which is why large pages can start to appear while they are still downloading.
Doing it by hand
You can send the same request without a browser. This Python script opens a TLS connection and writes the request text itself:
import socket
import ssl
host = "example.com"
request = (
"GET / HTTP/1.1\r\n"
f"Host: {host}\r\n"
"Accept: text/html\r\n"
"Connection: close\r\n"
"\r\n"
).encode("ascii")
context = ssl.create_default_context()
with socket.create_connection((host, 443)) as raw:
with context.wrap_socket(raw, server_hostname=host) as conn:
conn.sendall(request)
data = b""
while chunk := conn.recv(4096):
data += chunk
head, _, body = data.partition(b"\r\n\r\n")
print(head.decode("iso-8859-1"))
print("body bytes received:", len(body))The script sends Connection: close so the server closes the connection after replying, which ends the read loop. The script does not send Accept-Encoding, so the server should reply without compression. If the server uses chunked encoding, body also contains the chunk-size lines, so its length will be slightly larger than the real content.
Seeing it with curl
curl -v prints the request lines with > and the response lines with <:
curl -v https://example.com/ -o /dev/nullThe output also shows the DNS, TCP and TLS steps before the HTTP lines. Useful variations:
curl -I https://example.com/sends aHEADrequest and shows only the response headers.curl -H "Accept-Language: de" https://example.com/adds or overrides a header.curl --compressed -v https://example.com/sendsAccept-Encodingand decodes the reply.
In the browser's Network panel, selecting a request shows the same data on the Headers tab, split into request headers and response headers.
Common errors and edge cases
- Missing or wrong
Host. Typical results are400, or the response for a different site on the same server. - Wrong
Content-Type. A stylesheet served astext/plainis ignored in strict mode, and a script served astext/htmlmay be blocked. - Reading the body as text too early. Bodies are bytes. Decompress and decode them only after reading the headers.
HEADresponses. They includeContent-Lengthbut no body. A client that waits for those bytes hangs.- Responses with no body.
204 No Contentand304 Not Modifiednever have one, whatever the headers say. - Connection reuse. After a full response, HTTP/1.1 reuses the connection by default. A server that closes it unexpectedly forces the browser to retry the request on a new connection.
Exercise
A response has Content-Encoding: gzip and Content-Length: 400. The page is 1,000 bytes of HTML once decompressed. After reading the headers, how many body bytes does the browser read before it considers the response complete, and when does it decompress them?
Show answer
It reads 400 bytes, because Content-Length counts the bytes sent on the wire, which are the compressed ones. It decompresses the body after receiving the bytes, or while streaming them, and passes the resulting 1,000 bytes of HTML to the parser.
Exercise
Why does the request line contain only /docs/intro?lang=en and not the full URL, and how does the server still know which site is wanted?
Show answer
The scheme and host were used earlier to choose the connection (DNS, TCP and TLS), so the request line only needs the path and query. The Host header carries the site name, which lets one server and IP address host many sites.