Files
leetcode-go/笔试/微派 Test1/11-单选题9-Http响应头.md
T

110 lines
3.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
tags: [笔试, 微派, HTTP, 网络, Web]
create time: 2026-05-16 15:25
---
# 11 - 单选题 9:HTTP 响应头
## 题目
一个 HTTP 响应消息中,以下哪个响应头字段用于**告诉客户端(浏览器)在多久之内不需要再次请求该资源**?
| 选项 | 内容 |
|------|------|
| A | `Content-Length` |
| B | `Cache-Control: max-age=3600` |
| C | `Transfer-Encoding` |
| D | `Content-Type` |
<details>
<summary>点击查看答案与解析</summary>
### ✅ 正确答案:**B**
---
### 详细解析
#### 各字段的含义
```mermaid
flowchart LR
A["HTTP Response"] --> Header["响应头 Headers"]
Header --> BL["Content-Length: 表示主体字节数"]
Header --> CC["Cache-Control: 控制缓存行为"]
Header --> TE["Transfer-Encoding: 传输编码方式"]
Header --> CT["Content-Type: 媒体类型"]
```
#### 逐项分析
| 选项 | 正误 | 原因 |
|------|------|------|
| A | ❌ | `Content-Length` 只说明响应体的**字节大小**,和缓存无关 |
| B | ✅ **正确** | `Cache-Control: max-age=3600` 告诉浏览器:这个响应的响应体在**未来 3600 秒内**是新鲜的,可以直接使用本地缓存副本,无需向服务器发请求 |
| C | ❌ | `Transfer-Encoding` 指定了传输层的编码方式(如 `chunked`),用于不定长数据流式传输,与缓存无关 |
| D | ❌ | `Content-Type` 声明资源的媒体类型(如 `text/html`, `application/json`),让浏览器知道如何解析内容,不涉及缓存时效 |
#### Cache-Control 常用指令
| 指令 | 含义 |
|------|------|
| `max-age=N` | 资源在 N 秒内被认为是新鲜的 |
| `no-cache` | 不使用本地缓存(但可用),每次必须向服务器验证(条件请求) |
| `no-store` | 完全不允许缓存任何形式的内容 |
| `public` | 允许任意中间节点(CDN、代理、浏览器)缓存 |
| `private` | 只允许浏览器缓存,不能由 CDN/代理共享 |
| `s-maxage=N` | 只对共享缓存(如 CDN)生效,覆盖 `max-age` |
#### HTTP 缓存流程
```mermaid
sequenceDiagram
participant B as "浏览器 (Browser)"
participant S as "服务器 (Server)"
Note over B,S: 第一次请求
B->>S: GET /index.html
S-->>B: 200 OK + Cache-Control: max-age=3600
Note over B: 在接下来的 1小时内...
B->>B: 直接使用本地缓存! 不发请求 ✨
Note over B,S: 3600秒后
B->>S: GET /index.html (带 If-Modified-Since)
S-->>B: 304 Not Modified (无身体) ← 只返回头部确认
Note over B: 继续使用缓存并刷新计时器 ⏱️
```
#### HTTP 缓存的完整层级
```mermaid
graph TD
subgraph "强缓存 (不回服务器)"
BR["🌐 浏览器缓存"]
end
subgraph "协商缓存 (回服务器验证)"
CD["📡 CDN / Proxy"]
VS["🖥️ 验证服务器"]
end
BR -.->|命中 → 直接返回| DONE["✅ 200 (from disk/memory cache)"]
BR -.->|未命中 / 过期 →| CD
CD -.->|命中 → 直接返回| DONE
CD -.->|未命中 →| VS
VS -.->|304 Not Modified →| CD
CD -.->|转发给浏览器| DONE
VS -.->|200 OK + body →| CD
```
> [!note] 区分两个容易混淆的状态码
> - **200 (from memory cache)**: 浏览器从内存取,极快
> - **200 (from disk cache)**: 浏览器从硬盘取,稍慢
> - **304 Not Modified**: 协商缓存命中,服务器说"没变",客户端继续用旧副本
> [!tip] 面试常考组合
> `ETag` + `If-None-Match`: 实体标签机制。服务器通过计算内容的哈希值生成 ETag,客户端下次请求时带上 `If-None-Match: <etag>`。如果内容未变,服务器返回 304。这比 `Last-Modified` + `If-Modified-Since` 更精确(因为时间精度只有秒级)。
</details>