Bootstrap

HTTP报文详解:请求体、响应体及头部分类

HTTP报文详解:请求体、响应体及头部分类

1. 请求体格式

1.1 application/json

{
    "user": {
        "name": "John Doe",
        "age": 30,
        "email": "[email protected]",
        "preferences": {
            "theme": "dark",
            "notifications": true
        },
        "orders": [
            {
                "id": "12345",
                "amount": 99.99
            }
        ]
    }
}

1.2 application/x-www-form-urlencoded

username=johndoe&password=123456&remember=true

1.3 multipart/form-data

--boundary123456
Content-Disposition: form-data; name="username"

johndoe
--boundary123456
Content-Disposition: form-data; name="avatar"; filename="photo.jpg"
Content-Type: image/jpeg

[二进制文件数据]
--boundary123456--

1.4 text/plain

Hello, this is plain text content.
Multiple lines are allowed.

2. 响应体格式

2.1 application/json

{
    "status": "success",
    "code": 200,
    "data": {
        "id": 12345,
        "name": "Product Name",
        "price": 99.99,
        "description": "Product description",
        "images": [
            "url1.jpg",
            "url2.jpg"
        ],
        "metadata": {
            "created": "2024-03-21T10:00:00Z",
            "category": "electronics"
        }
    },
    "pagination": {
        "currentPage": 1,
        "totalPages": 10,
        "itemsPerPage": 20
    }
}

2.2 text/html

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>
<body>
    <h1>Welcome</h1>
    <p>This is a sample response.</p>
</body>
</html>

2.3 application/xml

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <status>success</status>
    <data>
        <user>
            <id>12345</id>
            <name>John Doe</name>
        </user>
    </data>
</response>

3. 请求头分类

3.1 客户端信息类

User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8
Accept-Encoding: gzip, deflate, br
DNT: 1

3.2 内容协商类

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Charset: utf-8
Content-Type: application/json
Content-Length: 1234

3.3 认证授权类

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Cookie: session=abc123; user=john
Origin: https://example.com
Referer: https://example.com/login

3.4 缓存控制类

If-Match: "686897696a7c876b7e"
If-None-Match: "686897696a7c876b7e"
If-Modified-Since: Wed, 21 Oct 2024 07:28:00 GMT
If-Unmodified-Since: Wed, 21 Oct 2024 07:28:00 GMT
Cache-Control: no-cache

3.5 连接管理类

Connection: keep-alive
Keep-Alive: timeout=5, max=1000
Upgrade: websocket

4. 响应头分类

4.1 服务器信息类

Server: nginx/1.18.0
Date: Thu, 21 Nov 2024 13:45:00 GMT
X-Powered-By: PHP/8.1.0
Via: 1.1 varnish

4.2 内容描述类

Content-Type: application/json; charset=utf-8
Content-Length: 1234
Content-Encoding: gzip
Content-Language: en-US
Content-Disposition: attachment; filename="report.pdf"

4.3 缓存控制类

Cache-Control: public, max-age=31536000
ETag: "686897696a7c876b7e"
Last-Modified: Wed, 21 Oct 2024 07:28:00 GMT
Expires: Thu, 22 Oct 2024 07:28:00 GMT
Vary: Accept-Encoding

4.4 安全类

Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Content-Security-Policy: default-src 'self'

4.5 Cookie管理类

Set-Cookie: session=abc123; Path=/; HttpOnly; Secure; SameSite=Strict
Set-Cookie: preference=dark; Max-Age=31536000

4.6 跨域控制类

Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Access-Control-Allow-Credentials: true

5. 特殊情况

5.1 重定向相关

Location: https://example.com/new-page
Refresh: 5; url=https://example.com/new-page

5.2 范围请求相关

# 请求头
Range: bytes=0-1024

# 响应头
Accept-Ranges: bytes
Content-Range: bytes 0-1024/2048

5.3 代理相关

# 请求头
Proxy-Authorization: Basic dXNlcjpwYXNz

# 响应头
Proxy-Authenticate: Basic realm="proxy"

让我解释一下API和application/json的关系:

  1. 什么是API:
  • API (Application Programming Interface) 是应用程序编程接口
  • 它是一种软件中间件,让不同的应用程序能够相互通信
  • API定义了如何进行这种通信的规则和格式
  1. 为什么用JSON格式:
// JSON格式示例
{
    "status": "success",
    "code": 200,
    "data": {
        "id": 1,
        "name": "iPhone",
        "price": 999.99
    }
}

特点:

  • 结构清晰:易于阅读和解析
  • 轻量级:数据量小,传输快
  • 跨语言:几乎所有编程语言都支持
  • 数据类型丰富:支持数字、字符串、布尔值、数组、对象等
  1. API响应的常见场景:
// 前端发起API请求
fetch('https://api.example.com/products/1')
    .then(response => response.json())
    .then(data => {
        console.log(data);
        // 使用返回的数据更新界面
    });

// 后端API处理
app.get('/api/products/:id', (req, res) => {
    const product = {
        id: req.params.id,
        name: "iPhone",
        price: 999.99
    };
    res.json(product);  // 返回JSON格式数据
});
  1. 与其他格式对比:
<!-- HTML格式:用于网页显示 -->
<div>
    <h1>iPhone</h1>
    <p>价格:$999.99</p>
</div>

<!-- XML格式:更verbose,数据量大 -->
<product>
    <id>1</id>
    <name>iPhone</name>
    <price>999.99</price>
</product>

// JSON格式:简洁清晰
{
    "id": 1,
    "name": "iPhone",
    "price": 999.99
}
  1. 实际应用举例:
// 1. 用户登录API
// POST /api/login
Request:
{
    "username": "john",
    "password": "123456"
}

Response:
{
    "status": "success",
    "token": "eyJhbGciOiJIUzI1...",
    "user": {
        "id": 123,
        "name": "John Doe",
        "email": "[email protected]"
    }
}

// 2. 商品列表API
// GET /api/products
Response:
{
    "total": 100,
    "page": 1,
    "pageSize": 10,
    "data": [
        {
            "id": 1,
            "name": "iPhone",
            "price": 999.99
        },
        {
            "id": 2,
            "name": "iPad",
            "price": 799.99
        }
    ]
}

// 3. 订单创建API
// POST /api/orders
Request:
{
    "productId": 1,
    "quantity": 2,
    "address": {
        "street": "123 Main St",
        "city": "New York",
        "zip": "10001"
    }
}

Response:
{
    "orderId": "ORD123456",
    "status": "created",
    "total": 1999.98,
    "createdAt": "2024-03-21T10:30:00Z"
}
  1. 为什么叫"API响应":
  • API是程序间的通信接口
  • JSON是当前最流行的API数据交换格式
  • 大多数Web API都使用JSON格式返回数据
  • 前端可以直接使用JSON格式的数据
  • 相比HTML(展示)和XML(复杂),JSON更适合API

所以说application/json是API响应,是因为:

  1. 它是API通信的标准格式
  2. 便于程序处理和解析
  3. 数据结构清晰明确
  4. 适合程序间的数据交换
  5. 已成为现代Web API的事实标准

这就是为什么我们说application/json是API响应的原因,它主要用于程序间的通信,而不是直接展示给用户看的内容。

以下文档是关键点:

  1. 请求体格式:
  • application/json:结构化数据
  • x-www-form-urlencoded:表单数据
  • multipart/form-data:文件上传
  • text/plain:纯文本
  1. 响应体格式:
  • application/json:API响应
  • text/html:网页内容
  • application/xml:XML数据
  1. 请求头分类:
  • 客户端信息类(User-Agent等)
  • 内容协商类(Accept等)
  • 认证授权类(Authorization等)
  • 缓存控制类(If-Match等)
  • 连接管理类(Connection等)
  1. 响应头分类:
  • 服务器信息类(Server等)
  • 内容描述类(Content-Type等)
  • 缓存控制类(Cache-Control等)
  • 安全类(X-Frame-Options等)
  • Cookie管理类(Set-Cookie)
  • 跨域控制类(Access-Control-Allow-Origin等)
;