HTTP报文
用于 HTTP 协议交互的信息被称为 HTTP 报文。请求端(客户端)的HTTP 报文叫做请求报文,响应端(服务器端)的叫做响应报文。HTTP报文本身是由多行(用 CR+LF 作换行符)数据构成的字符串文本。
HTTP 报文大致可分为报文首部和报文主体两块。两者由最初出现的空行(CR+LF)来划分。通常,并不一定要有报文主体。

请求报文和响应报文的结构
我们来看一下请求报文和响应报文的结构。


1. 基本 GET 请求
请求
GET /index.html HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
响应
HTTP/1.1 200 OK
Date: Mon, 07 Jul 2025 08:00:00 GMT
Server: Apache/2.4.41 (Unix)
Content-Type: text/html; charset=UTF-8
Content-Length: 1234
<!DOCTYPE html>
<html>
<head>
<title>Example Domain</title>
</head>
<body>
<h1>Welcome to Example.com</h1>
</body>
</html>
2. 带查询参数的 GET 请求
请求
GET /search?query=apple&category=fruits HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
Accept: application/json
响应
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 156
{
"results": [
{"name": "Red Apple", "price": 2.50},
{"name": "Green Apple", "price": 2.30}
],
"total": 2
}
3. 请求不存在的资源
请求
GET /nonexistent-page.html HTTP/1.1
Host: example.com
响应
HTTP/1.1 404 Not Found
Content-Type: text/html
Content-Length: 325
<!DOCTYPE html>
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body>
</html>
4. 带请求头的 GET 请求
请求
GET /api/data HTTP/1.1
Host: example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Accept: application/json
X-Custom-Header: custom-value
响应
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-cache
{
"message": "Authenticated data response",
"timestamp": "2025-07-07T08:00:00Z"
}
=========================================================================
请求报文和响应报文的首部内容由以下数据组成。现在出现的各种首部字段及状态码稍后会进行阐述。
请求行:包含用于请求的方法,请求 URI 和 HTTP 版本。
状态行:包含表明响应结果的状态码,原因短语和 HTTP 版本。
首部字段:包含表示请求和响应的各种条件和属性的各类首部。一般有 4 种首部,分别是:通用首部、请求首部、响应首部和实体首部。
其他:可能包含 HTTP 的 RFC 里未定义的首部(Cookie 等)。
编码提升传输效率
HTTP 在传输数据时可以按照数据原貌直接传输,但也可以在传输过程中通过编码提升传输速率。通过在传输时编码,能有效地处理大量的访问请求。但是,编码的操作需要计算机来完成,因此会消耗更多的CPU 等资源。