# ch03: HTTP Messages

![3.HTTP报文](https://tva1.sinaimg.cn/large/007S8ZIlly1gga2zgiktjj316n0u0tfq.jpg)

## 0. Guide

* How messages flow
* The three parts of HTTP messages(start line, headers, and entity body)
* The different parts of HTTP request and response messages
* The various functions(methods) that request messages support
* The various status codes that are returned with response messages
* What the various HTTP headers do

## 1. The Flow of Messages

### **1.1 Messages Commute Inbound to the Origin Server**

HTTP uses the terms ***inbound*** and ***outbound*** to describe ***transactional*** direction:

![](http://ww1.sinaimg.cn/large/006tNc79ly1g5d991ulryj31kc0lu0y1.jpg)

### **1.2 Messages Flow Downstream**

HTTP messages flow like rivers. All messages flow, *downstream*, regardless of whether they are request messages or response messages. The sender of any message is *upstream* of the receiver:

![](http://ww4.sinaimg.cn/large/006tNc79ly1g5dcmard1rj31320u0aj5.jpg)

## 2. The Parts of a Message

Messages consist of three parts: *start line* describing the message, a block of *headers* containing attributes, and an optional *body* containing data: ![](http://ww3.sinaimg.cn/large/006tNc79ly1g5dctxwmmbj31ke0fkn0n.jpg)

### **2.1 Message Syntax**

Here's the format for a request message:

```
<method> <request-URL> <version>
<headers>

<entity-body>
```

Here's the format for a response message:

```
<version> <status> <reason-phrase>
<headers>

<entity-body>
```

![](http://ww1.sinaimg.cn/large/006tNc79ly1g5gszpcyrcj31k20hkgp7.jpg)

### **2.2 Start Lines**

The start line for a request message says *what to do*. The start line for a response message says *what happended*.

**2.2.1 Request line**

*Request line* contains a method, a request URL and HTTP version.

**2.2.2 Response line**

*Response line* contains the HTTP version, a numeric status code and a textual reason phrase.

**2.2.3 Methods**

Common HTTP methods:

| Method  | Description                                            | Message body? |
| ------- | ------------------------------------------------------ | ------------- |
| GET     | Get a document from the server.                        | No            |
| HEAD    | Get just the headers for a document from the server.   | No            |
| POST    | Send data to the server for processing.                | Yes           |
| PUT     | Store the body of the request on the server.           | Yes           |
| TRACE   | Trace the message through proxy servers to the server. | No            |
| OPTIONS | Determine what methods can operate on a server.        | No            |
| DELETE  | Remove a document from the server.                     | No            |

Not all servers implement all seven of the methods. HTTP was designed to be easily extensible, other servers may implement their own request methods in addition to these, called *extension methods*.

**2.2.4 Status codes**

Status code classes:

| Overrall range | Defined range | Category      |
| -------------- | ------------- | ------------- |
| 100-199        | 100-101       | Informational |
| 200-299        | 200-206       | Successful    |
| 300-399        | 300-305       | Redirection   |
| 400-499        | 400-415       | Client error  |
| 500-599        | 500-505       | Server error  |

**2.2.5 Version numbers**

The version number indicates the highest version of HTTP that an application supports.

Note that version numbers are not treated as fractional numbers. Each number in the version is treated as a sepatate number. So, when comparing HTTP versions, each number must be compared separately in order to determine which is the higher version. For example, HTTP /2.22 is a higher version than HTTP/2.3, because 22 is a larger number than 3.

### **2.3 Headers**

HTTP header fields add additional information to request and response messages.

**2.3.1 Header classfications**

The HTTP specification defines several header fields. Applications also are free to invent their own home-brewed headeres. HTTP headers are classified into:

*General headers*

​ Can appear in both request and response messages.

*Request headers*

​ Provide more information about the request.

*Response headers*

​ Provide more information about the response.

*Entity headers*

​ Describe body size and contents, or the resource itself.

*ESxtension headers*

​ New headers that are not defined in the specification.

Common header examples:

| Header example                           | Description                                     |
| ---------------------------------------- | ----------------------------------------------- |
| Date: Tue, 3 Oct 1997 02:16:03 GMT       | The date the server generated the response      |
| Content-length: 15040                    | The entity body contains 15040 bytes of data    |
| Content-type: image/gif                  | The entity body is a GIF image                  |
| Accept: image/gif, image/jpec, text/html | The client accepts GIF and JPEG images and HTML |

**2.3.2 Header continuation lines**

Long header lines can be made more readable by breaking them into multiple lines, preceding each extra line with at least one space or tab character:

```
HTTP/1.0 200 OK
Content-Type: image/gif
Content-Length: 8572
Server: Test Server
    Version 1.0
```

### **2.4 Entity Bodies**

Optional. Entity bodies are the payload of HTTP messages. They are the things that HTTP was designed to transport.

### **2.5 Version 0.9 Messages**

A far simpler protocol:

![](http://ww1.sinaimg.cn/large/006tNc79ly1g5guktexhtj31k80paahz.jpg)

## 3. Methods

To be compliant with HTTP Version 1.1, a server need implement only the GET and HEAD methods for its resources.

### **3.1 Safe Methods**

HTTP defines a set of methods that are called *safe* methods. The GET and HEAD methods are said to be safe, meaning that no action should occur as a result of an HTTP request that uses either the GET or HEAD method.

### **3.2 GET**

GET is the most common method. It usually is used to ask a server to send a resource. HTTP/1.1 requires to implement this method:

![](http://ww1.sinaimg.cn/large/006tNc79ly1g5gv4qguo1j31k00midm2.jpg)

### **3.3 HEAD**

The HEAD method behaves esxactly like the GET method, but the server returns only the headers in the response. This allows a client to inspect the headers for a resource without having to actually get the resource. Using HEAD, you can:

* Find out about a resource(e.g., determine its type) without getting it.
* See if an object exists, by looking at the status code of the response.
* Test if the resource has been modified, by looking at the headers.

![](http://ww4.sinaimg.cn/large/006tNc79ly1g5gvenppwmj31k20jmwki.jpg)

### **3.4 PUT**

The PUT method writes documents to a server:

![](http://ww4.sinaimg.cn/large/006tNc79ly1g5gvhpu3unj31ju0s211a.jpg)

The semantics of the PUT method are for the server to take the body of the request and either use it to create a new document named by the requested URL or, if that URL already exists, use the body to replace it.

### **3.5 POST**

The POST method was designed to send input data to the server. In practice, it is often used to support HTML forms:

![](http://ww2.sinaimg.cn/large/006tNc79ly1g5gvlxifg7j30x80u0nb0.jpg)

### **3.6 TRACE**

When a client makes a request, that request may have to travel through firewalls, proxies, gateways, or other applications. Each of these has the opportunity to modify the original HTTP request. The TRACE method allows clients to see how its request looks when it finally makes it to the server:

![](http://ww4.sinaimg.cn/large/006tNc79ly1g5gzbmstizj31f10u0al8.jpg)

The TRACE method is used primarily for diagnostics.

No entity body can be sent with a TRACE request. The entity body of the TRACE response contains, verbatim, the request that the responding server received.

### **3.7 OPTIONS**

The OPTIONS method asks the server to tell us about the various supported capabilitites of the web server:

![](http://ww1.sinaimg.cn/large/006tNc79ly1g5gzg0x94ij31jm0lwjxx.jpg)

### **3.8 DELETE**

The DELETE method asks the server to delete the resources specified by the request URL. The HTTP specification allows the server to override the request without telling the client:

![](http://ww3.sinaimg.cn/large/006tNc79ly1g5gzhuxvetj31jy0ooahn.jpg)

### **3.9 Extension Methods**

If you define an extension method, it's likely not to be understood by most HTTP applications. Likewise, it's possible that your HTTP applications could run into extension methods being used by other applications that it does not understand.

Proxies should try to relay messages with unknown methods through to downstream servers if they are capable of doing that without breaking end-to-end behavior.

## 4. Status Codes

### **4.1 100-199: Informational Status Codes**

| Status code | Reason phrase       | Meaning                                                                                                                                                             |
| ----------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 100         | Continue            | Indicates that an initial part of the request was received and the client should continue. After sending this, the server must respond after receiving the request. |
| 101         | Switching Protocols | Indicates that the server is changing protocols, as specified by the client, to one listed in the Upgrade header.                                                   |

**4.1.1 Clients and 100 Continue**

If a client is sending an entity to a server and is willing to wait for a 100 Continue response before it sends the entity, the client needs to send an Except request header with the value 100-continue.

A client application should really use 100-continue only to avoid sending a server a large entity that the server will not be able to handle or use.

Clients that send an Except header for 100-continue should not wait forever for the server to send a 100 Continue response. After some timeout, the client should just send the entity.

**4.1.2 Servers and 100 Continue**

When receiving the Expect header and 100-continue value, the server should respond with either 100 Continue response or an error code.

### **4.2 200-299: Success Status Codes**

| Status code | Reason phrase                 | Meaning                                                                                                                                                                                                               |
| ----------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 200         | OK                            | Request is okay.                                                                                                                                                                                                      |
| 201         | Created                       | For requests that create server objects(PUT). The entity body of the response should contain the various URLs for referencing the created resource, with the Localtion header cantaining the most specific reference. |
| 202         | Accepted                      | The request was accepted, but the server has not yet performed any action with it. There are no guarantees that the server will complete the request; this just means that the request looked valid when accepted.    |
| 203         | Non-Authoritative Information |                                                                                                                                                                                                                       |
| 204         | No Content                    |                                                                                                                                                                                                                       |
| 205         | Reset Content                 | Another code primarily for browsers. Tells the browser to clear any HTML form elements on the current page.                                                                                                           |
| 206         | Partial Content               | A partial or *range* request was successful.                                                                                                                                                                          |

### **4.3 300-399: Redirection Status Codes**

The redirection status codes either tell clients to use alternate locations for the resources they're interested in or provide an alternate response instead of the content:

![](http://ww3.sinaimg.cn/large/006tNc79ly1g5h1cycurpj30u00w97fj.jpg)

If-Modified-Since:

![](http://ww2.sinaimg.cn/large/006tNc79ly1g5h1l9syhjj30xw0u04bd.jpg)

| Status code | Reason phrase      |
| ----------- | ------------------ |
| 300         | Multiple Choices   |
| 301         | Moved Permanently  |
| 302         | Found              |
| 303         | See Other          |
| 304         | Not Modified       |
| 305         | Use Proxy          |
| 306         | (Unused)           |
| 307         | Temporary Redirect |

### **4.4 400-499： Client Error Status Codes**

| Status code | Reason phrase                    |
| ----------- | -------------------------------- |
| 400         | Bad Request                      |
| 401         | Unauthorized                     |
| 402         | Payment Required                 |
| 403         | Forbidden                        |
| 404         | Not Found                        |
| 405         | Method Not Allowed               |
| 406         | Not Acceptable                   |
| 407         | Proxy Authentication Required    |
| 408         | Request Timeout                  |
| 409         | Conflict                         |
| 410         | Gone                             |
| 411         | Length Required                  |
| 412         | Precondition Failed              |
| 413         | Request Entity Too Large         |
| 414         | Request URI Too Long             |
| 415         | Unsupported Media Type           |
| 416         | Requested Range Not Statisfiable |
| 417         | Exception Failed                 |

### **4.5 500-599: Server Error Status Codes**

| Status code | Reason phrase              |
| ----------- | -------------------------- |
| 500         | Internal Server Error      |
| 501         | Not Implemented            |
| 502         | Bad Gateway                |
| 503         | Service Unavailable        |
| 504         | Gateway Timeout            |
| 505         | HTTP Version Not Supported |

## 5. Headers

Headers and methods work together to determine what clients and servers do.

*General headers*

​ These are generic headers used by both clients and servers.

*Request headers*

​ Are specific to request messages, providing extra information to servers.

*Response headers*

​ Provide information to the client.

*Entity headers*

​ Deal with the entity body.

*Extension headers*

​ HTTP programs need to tolerate and forward extension headers, even if they don't know what the headers mean.

### **5.1 General Headers**

| Header            | Description                                                                                               |
| ----------------- | --------------------------------------------------------------------------------------------------------- |
| Connection        | Allows clients and servers to specify options about the request/response connection                       |
| Date              | Provides a date and time stamp telling when the message was created                                       |
| MIME-Version      | Gives the version of MIME that the sender is using                                                        |
| Trailer           | Lists the sest of headers that are in the trailer of a message encoded with the chunked transfer encoding |
| Transfer-Encoding | Tells the receiver what encoding was performed on the message in order for it to be transported safely    |
| Upgrade           | Gives a new version or protocol that the sendesr would like to "upgrade" to using                         |
| Via               | Shows what intermediaries(proxies, gateways) the message has gone through                                 |
| Cache-Control     | Used to pass caching directions along with the message                                                    |
| Pragma            | Another way to pass directions along with the message, though not specific to caching                     |

### **5.2 Request Headers**

| Header     | Description                                                                  |
| ---------- | ---------------------------------------------------------------------------- |
| Client-IP  | Provides the IP address of the machine on which the client is running        |
| From       | Provides the email address of the client's user                              |
| Host       | Gives the hostname and port of the server to which the request is being sent |
| Referer    | Provides the URL of the document that contains the current request URI       |
| User-Agent | Tells the server the name of the application making the request              |

Accept headers give the client a way to tell servers their preferences and capabilities.

| Header          | Description                                                      |
| --------------- | ---------------------------------------------------------------- |
| Accept          | Tells the server what media types are okay to send               |
| Accept-Charset  | Tells the server what charsets are okay to send                  |
| Accept-Encoding | Tells the server what encodings are okay to send                 |
| Accept-Language | Tells the server what languages are okay to send                 |
| TE              | Tells the server what extension transfer codings are okay to use |

### **5.3 Response Headers**

| Header | Description                                                     |
| ------ | --------------------------------------------------------------- |
| Age    | How old the response is                                         |
| Public | A list of request methods the server supports for its resources |
| Server | The name and version of the server's application software       |

### **5.4 Entity Headers**

| Header   | Description                                                                                                         |
| -------- | ------------------------------------------------------------------------------------------------------------------- |
| Allow    | Lists the reqeust methods that can be performed on this entity                                                      |
| Location | Tells the client  where the entity really is located; used in direction the receiver to a location for the resource |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://valineliu.gitbook.io/deuterium-wiki/reading/cs-jing-dian-shu-ji/http/ch03-http-messages.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
