HTTP(HyperText Transfer Protocol,超文本传输协议)是 Web 开发的基础协议。理解 HTTP 协议对于构建 Web 应用至关重要。
HTTP 是一个无状态的请求-响应协议,客户端向服务器发送请求,服务器返回响应。
- 无状态:每个请求都是独立的,服务器不保存客户端状态
- 请求-响应模式:客户端发起请求,服务器返回响应
- 可扩展:通过头部字段可以扩展功能
- 简单:人类可读的消息格式
GET /api/users HTTP/1.1
Host: api.example.com
User-Agent: Mozilla/5.0
Accept: application/json
Content-Type: application/json
{"name": "张三", "email": "zhangsan@example.com"}
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 123
Date: Mon, 23 May 2023 22:38:34 GMT
{
"id": 1,
"name": "张三",
"email": "zhangsan@example.com",
"created_at": "2023-05-23T22:38:34Z"
}
| 状态码 | 类别 | 说明 |
|---|---|---|
| 200 | 成功 | 请求成功 |
| 201 | 成功 | 创建成功 |
| 400 | 客户端错误 | 请求参数错误 |
| 401 | 客户端错误 | 未授权 |
| 403 | 客户端错误 | 禁止访问 |
| 404 | 客户端错误 | 资源不存在 |
| 500 | 服务器错误 | 服务器内部错误 |
Host: 服务器域名User-Agent: 客户端信息Accept: 接受的响应类型Content-Type: 请求体类型Authorization: 认证信息
Content-Type: 响应体类型Content-Length: 响应体长度Set-Cookie: 设置 CookieCache-Control: 缓存控制
REST(Representational State Transfer)是一种软件架构风格,用于设计网络应用程序的 API。
- 无状态:每个请求包含所有必要信息
- 统一接口:使用标准 HTTP 方法
- 资源导向:API 围绕资源设计
- 可缓存:响应可以被缓存
- 分层系统:支持代理、网关等中间层
| 方法 | 用途 | 幂等性 |
|---|---|---|
| GET | 获取资源 | ✅ |
| POST | 创建资源 | ❌ |
| PUT | 更新资源 | ✅ |
| PATCH | 部分更新 | ❌ |
| DELETE | 删除资源 | ✅ |
# 用户资源
GET /api/users # 获取用户列表
POST /api/users # 创建新用户
GET /api/users/{id} # 获取特定用户
PUT /api/users/{id} # 更新用户
DELETE /api/users/{id} # 删除用户
# 用户文章资源
GET /api/users/{id}/posts # 获取用户的文章
POST /api/users/{id}/posts # 为用户创建文章
import requests
# GET 请求
response = requests.get('https://api.example.com/users')
users = response.json()
# POST 请求
data = {'name': '张三', 'email': 'zhangsan@example.com'}
response = requests.post('https://api.example.com/users', json=data)
new_user = response.json()
# 带认证的请求
headers = {'Authorization': 'Bearer your-token'}
response = requests.get('https://api.example.com/profile', headers=headers)// Fetch API
fetch('https://api.example.com/users')
.then(response => response.json())
.then(data => console.log(data));
// POST 请求
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: '张三',
email: 'zhangsan@example.com'
})
})
.then(response => response.json())
.then(data => console.log(data));使用浏览器开发者工具或 Postman 分析以下请求:
- 访问 GitHub 首页
- 搜索一个仓库
- 查看仓库详情
记录请求方法、URL、状态码和响应内容。
import socket
def send_http_request(host, port, path):
# 创建 socket 连接
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
# 构建 HTTP 请求
request = f"GET {path} HTTP/1.1\r\n"
request += f"Host: {host}\r\n"
request += "Connection: close\r\n"
request += "\r\n"
# 发送请求
sock.send(request.encode())
# 接收响应
response = b""
while True:
data = sock.recv(1024)
if not data:
break
response += data
sock.close()
return response.decode()
# 使用示例
response = send_http_request('httpbin.org', 80, '/get')
print(response)完成本节学习后,请检查是否掌握:
- HTTP 协议的基本工作原理
- 请求和响应的结构
- 常见状态码的含义
- RESTful API 设计原则
- 能够发送和分析 HTTP 请求
上一节:第一章目录 | 下一节:1.2 Web 框架入门