提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
HTTP (Hypertext Transfer Protocol) 是互联网上应用最广泛的协议之一,用于客户端和服务器之间的通信。
HTTP 请求方法
GET
用途:请求获取指定资源
-
特点:
-
参数通过 URL 传递
可以被缓存
有长度限制
不应修改服务器数据
示例:
GET /users?id=123 HTTP/1.1
Host: example.com
POST
用途:提交数据到指定资源进行处理
-
特点:
-
数据在请求体中传输
不会被缓存
无长度限制
可能修改服务器数据
示例:
POST /users HTTP/1.1
Host: example.com
Content-Type: application/json
{"name":"John","age":30}
PUT
用途:更新指定资源
-
特点:
-
幂等操作(多次执行结果相同)
替换整个资源
示例:
PUT /users/123 HTTP/1.1
Host: example.com
Content-Type: application/json
{"name":"John","age":31}
DELETE
用途:删除指定资源
-
特点:
- 幂等操作
示例:
DELETE /users/123 HTTP/1.1
Host: example.com
其他方法
HEAD:类似 GET,但只返回头部信息
PATCH:部分更新资源
OPTIONS:返回服务器支持的 HTTP 方法
HTTP 请求结构
-
一个完整的 HTTP 请求包含:
-
请求行(方法、URI、HTTP版本)
请求头(Host, Content-Type, Authorization等)
空行
请求体(GET通常没有,POST/PUT有)
常用请求头
Content-Type: 请求体的媒体类型(如 application/json)
Accept: 客户端能处理的媒体类型
Authorization: 认证信息
User-Agent: 客户端信息
Cache-Control: 缓存控制
实际应用示例
使用 cURL 发送请求
# GET
curl https://api.example.com/users
# POST
curl -X POST -H "Content-Type: application/json" -d '{"name":"John"}' https://api.example.com/users
# PUT
curl -X PUT -H "Content-Type: application/json" -d '{"name":"John"}' https://api.example.com/users/1
# DELETE
curl -X DELETE https://api.example.com/users/1
使用 Python (requests 库)
import requests
# GET
response = requests.get('https://api.example.com/users')
# POST
response = requests.post('https://api.example.com/users', json={'name': 'John'})
# PUT
response = requests.put('https://api.example.com/users/1', json={'name': 'John'})
# DELETE
response = requests.delete('https://api.example.com/users/1')
响应状态码
1xx: 信息响应
2xx: 成功(200 OK, 201 Created)
3xx: 重定向
4xx: 客户端错误(400 Bad Request, 404 Not Found)
5xx: 服务器错误(500 Internal Server Error)