HTTP 协议的请求和响应报文中必定包含 HTTP 首部。首部内容为客户端和服务器分别处理请求和响应提供所需要的信息。首部由请求行/响应行和首部字段组成。
HTTP 首部字段的结构
HTTP 首部字段由首部字段名和字段值构成,中间用英文冒号:
分割。
若HTTP 首部字段重复了会如何
当HTTP 报文首部中出现了两个或两个以上具有相同首部字段名时会怎么样?这种情况在规范内尚未明确,根据浏览器内部处理逻辑的不同,结果可能并不一致。有些浏览器会优先处理第一次出现的首部字段,而有些则会优先处理最后出现的首部字段,有些会把先后出现的字段值理解为逗号分割的多个值。
HTTP 首部字段一览
HTTP 首部字段根据实际用途被分为以下 4 种类型。
- 通用首部字段:请求报文和响应报文两方都会使用的首部。
- 请求首部字段:从客户端向服务器端发送请求报文时使用的首部。补充了请求的附加内容、客户端信息、响应内容相关优先级等信息。
- 响应首部字段:从服务器端向客户端返回响应报文时使用的首部。补充了响应的附加内容,也会要求客户端附加额外的内容信息。
- 实体首部字段:针对请求报文和响应报文的实体部分使用的首部。补充了资源内容更新时间等与实体有关的信息。
通用首部字段
首部字段名 | 说明 |
---|---|
Cache-Control | 控制缓存的行为,详见 HTTP协议——客户端缓存协商 |
Connection | 连接的管理 |
Date | 创建报文的日期时间 |
Pragma | HTTP1.0中被定义为可扩展字段,目前只用于发送no-cache 指令 |
Trailer | 允许发送方在分块发送的消息后面添加额外的元信息,这些元信息可能是随着消息主体的发送动态生成的,比如消息的完整性校验,消息的数字签名,或者消息经过处理之后的最终状态等 |
Transfer-Encoding | 规定传输报文主体时采用的编码方式,逐跳首部(区别于端到端首部Content-Encoding) 。详见HTTP协议——响应内容压缩 |
Upgrade | 升级为其他协议 |
Via | 记录每一级代理服务器的信息;可以追踪客户端与服务器之间的请求和响应报文的传输路径,还可以防止请求回环 |
Warning | 通常会告知用户一些与缓存相关的错误警告 |
请求首部字段
首部字段名 | 说明 |
---|---|
Accept | 用户代理可接受的媒体类型,可以使用q=[权重] 表示权重优先级,取值范围0-1,默认为1,值越大优先级越高,相同权重靠前的优先 |
Accept-Charset | 可接受的字符集。支持权重设置 |
Accept-Encoding | 可接受的内容压缩编码。支持权重设置 |
Accept-Language | 可接受的语言(自然语言)。支持权重设置 |
Authorization | Web认证信息 |
Expect | 期待服务器的特定行为,HTTP1.1规范中只定义了100-continue |
From | 用户的电子邮箱地址 |
Host | 请求资源所在服务器 |
If-Modified-Since | 比较资源的更新时间。有更新则返回最新的资源,否则返回304(资源未更新)状态 |
If-None-Match | 比较Etag标记。不匹配则返回最新的资源,否则返回304(资源未更新)状态 |
If-Range | 比较Etag标记或者比较资源时间。资源未更新时返回206状态码,并发送实体 Byte 的范围请求,否则返回200并发送全部资源 |
If-Match | 比较实体标记(ETag)。匹配则响应请求(GET或POST、PUT等请求均可),否则返回412状态(先决条件失败),用在Range范围请求时,如果失败则需要客户端再次发起请求 |
If-Unmodified-Since | 比较资源的更新时间。没有更新则响应请求(GET或POST、PUT等请求均可),否则返回412状态(先决条件失败),用在Range范围请求时,如果失败则需要客户端再次发起请求 |
Max-Forwards | 最大传输逐跳数,即经过的代理服务器个数 |
Proxy-Authorization | 代理服务器要求客户端的认证信息 |
Range | 实体的字节范围请求,请求的范围不合法则服务端返回416(请求范围无法满足)状态 |
Referer | 对请求中 URI 的原始获取方 |
TE | 传输编码的优先级 |
User-Agent | HTTP 客户端程序的信息 |
响应首部字段
首部字段名 | 说明 |
---|---|
Accept-Ranges | 是否接受字节范围请求 |
Age | 推算资源创建经过时间 |
ETag | 资源的匹配信息 |
Location | 令客户端重定向至指定URI |
Proxy-Authenticate | 代理服务器对客户端的认证信息 |
Retry-After | 对再次发起请求的时机要求 |
Server | HTTP服务器的安装信息 |
Vary | 代理服务器缓存的管理信息 |
Www-Authenticate | 服务器对客户端的认证信息 |
实体首部字段
首部字段名 | 说明 |
---|---|
Allow | 资源可支持的HTTP方法 |
Content-Encoding | 实体主体适用的编码方式 |
Content-Language | 实体主体的自然语言 |
Content-Length | 实体主体的大小(单位:字节) |
Content-Location | 替代对应资源的URI |
Content-MD5 | 实体主体的报文摘要 |
Content-Range | 实体主体的位置范围 |
Content-Type | 实体主体的媒体类型 |
Expires | 实体主体过期的日期时间 |
Last-Modified | 资源的最后修改日期时间 |