HTTP response format

Like the HTTP request, the HTTP response also consists of a header part and a body part. Also similar to the HTTP request, the body part is optional. Most HTTP responses do have a body part, though.

The server at www.example.com could respond to our HTTP request with the following reply:

HTTP/1.1 200 OK
Cache-Control: max-age=604800
Content-Type: text/html; charset=UTF-8
Date: Fri, 14 Dec 2018 16:46:09 GMT
Etag: "1541025663+gzip"
Expires: Fri, 21 Dec 2018 16:46:09 GMT
Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT
Server: ECS (ord/5730)
Vary: Accept-Encoding
X-Cache: HIT
Content-Length: 1270

<!doctype html>
<html>
<head>
<title>Example Domain</title>
...

The first line of an HTTP response is the status line. The status line consists of the protocol version, the response code, and the response code description. In the preceding example, we can see that the protocol version is HTTP/1.1, the response code is 200, and the response code description is OK. 200 OK is the typical response code to an HTTP GET request when everything goes ok. If the server couldn't find the resource the client has requested, it might respond with a 404 Page Not Found response code instead.

Many of the HTTP response headers are used to assist with caching. The Date, Etag, Expires, and Last-Modified fields can all be used by the client to cache documents.

The Content-Type field tells the client what type of resource it is sending. In the preceding example, it is an HTML web page, which is specified with text/html. HTTP can be used to send all types of resources, such as images, software, and videos. Each resource type has a specific Content-Type, which tells the client how to interpret the resource.

The Content-Length field specifies the size of the HTTP response body in bytes. In this case, we see that the requested resource is 1270 bytes long. There are a few ways to determine the body length, but the Content-Length field is the simplest. We will look at other ways in the Response Body Length section later in this chapter.

The HTTP response header section is delineated from the HTTP response body by a blank line. After this blank line, the HTTP body follows. Note that the HTTP body is not necessarily text-based. For example, if the client requested an image, then the HTTP body would likely be binary data. Also consider that, if the HTTP body is text-based, such as an HTML web page, it is free to use its own line-ending convention. It doesn't have to use the \r\n line ending required by HTTP.

If the client had sent a HEAD request type instead of GET, then the server would respond with exactly the same HTTP headers as before, but it would not include the HTTP body.

With the HTTP response format defined, let's look at some of the most common HTTP response types.