This article is not available in your language yet. Showing the zh-CN version.
API 测试与调试指南:从 cURL 到在线工具的接口调试全攻略
Dev Tools(Updated Jun 2, 2026)
HTTP 请求方法
| 方法 | 用途 | 幂等 | 安全 |
|---|---|---|---|
| GET | 获取资源 | ✅ | ✅ |
| POST | 创建资源 | ❌ | ❌ |
| PUT | 全量更新 | ✅ | ❌ |
| PATCH | 部分更新 | ❌ | ❌ |
| DELETE | 删除资源 | ✅ | ❌ |
| HEAD | 获取头信息 | ✅ | ✅ |
| OPTIONS | 跨域预检 | ✅ | ✅ |
常用请求头
| 头部 | 说明 | 示例 |
|---|---|---|
Content-Type |
请求体格式 | application/json |
Accept |
期望的响应格式 | application/json |
Authorization |
认证信息 | Bearer token... |
User-Agent |
客户端标识 | Mozilla/5.0... |
Cookie |
Cookie | session=abc123 |
X-Request-ID |
请求追踪 ID | UUID |
Content-Type 常见值
| 值 | 用途 |
|---|---|
application/json |
JSON 数据 |
application/x-www-form-urlencoded |
表单数据 |
multipart/form-data |
文件上传 |
text/plain |
纯文本 |
text/html |
HTML |
认证方式
1. Bearer Token(最常用)
# cURL
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..." \
https://api.example.com/users
# JavaScript
fetch('https://api.example.com/users', {
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiJ9...',
},
});
2. Basic Auth
# cURL(自动编码)
curl -u username:password https://api.example.com/users
# 手动编码
# Base64("username:password") = "dXNlcm5hbWU6cGFzc3dvcmQ="
curl -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" \
https://api.example.com/users
3. API Key
# 方式一:Header
curl -H "X-API-Key: your-api-key" \
https://api.example.com/users
# 方式二:Query 参数
curl "https://api.example.com/users?api_key=your-api-key"
cURL 命令详解
基础 GET 请求
# 最简单的 GET
curl https://api.example.com/users
# 显示响应头
curl -i https://api.example.com/users
# 只显示响应头
curl -I https://api.example.com/users
# 跟随重定向
curl -L https://example.com/redirect
POST 请求
# JSON 数据
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice", "email": "alice@example.com"}'
# 表单数据
curl -X POST https://api.example.com/users \
-d "name=Alice&email=alice@example.com"
# 文件上传
curl -X POST https://api.example.com/upload \
-F "file=@photo.jpg" \
-F "description=My photo"
高级选项
# 超时设置
curl --connect-timeout 5 --max-time 30 https://api.example.com
# 输出到文件
curl -o response.json https://api.example.com/users
# 静默模式(不显示进度)
curl -s https://api.example.com/users
# 详细输出(调试用)
curl -v https://api.example.com/users
# 忽略 SSL 证书验证(仅开发环境)
curl -k https://self-signed.example.com
# 代理
curl -x http://proxy:8080 https://api.example.com
# Cookie
curl -b "session=abc123" https://api.example.com/users
# 保存和发送 Cookie
curl -c cookies.txt -b cookies.txt https://api.example.com/users
常见 HTTP 状态码
| 状态码 | 含义 | 常见原因 |
|---|---|---|
| 200 | OK | 成功 |
| 201 | Created | POST 创建成功 |
| 204 | No Content | DELETE 成功 |
| 301 | Moved Permanently | 永久重定向 |
| 304 | Not Modified | 缓存命中 |
| 400 | Bad Request | 参数错误 |
| 401 | Unauthorized | 未认证 |
| 403 | Forbidden | 无权限 |
| 404 | Not Found | 资源不存在 |
| 409 | Conflict | 资源冲突 |
| 422 | Unprocessable Entity | 验证失败 |
| 429 | Too Many Requests | 限流 |
| 500 | Internal Server Error | 服务端错误 |
| 502 | Bad Gateway | 上游服务不可用 |
| 503 | Service Unavailable | 服务过载 |
使用工具库测试 API
cURL 转代码
- 打开 cURL 转代码工具
- 粘贴 cURL 命令
- 选择目标语言(JavaScript/Python/Go/Java 等)
- 复制生成的代码
示例
# 输入 cURL
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-H "Authorization: Bearer token123" \
-d '{"name": "Alice"}'
转换为 JavaScript:
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123',
},
body: JSON.stringify({ name: 'Alice' }),
});
const data = await response.json();
API 调试技巧
1. 查看完整请求/响应
# -v 显示详细信息
curl -v https://api.example.com/users
# 输出:
> GET /users HTTP/1.1 ← 请求行
> Host: api.example.com ← 请求头
> Authorization: Bearer ...
>
< HTTP/1.1 200 OK ← 响应行
< Content-Type: application/json ← 响应头
< X-RateLimit-Remaining: 99
<
[{"id": 1, "name": "Alice"}] ← 响应体
2. 格式化 JSON 响应
# 使用 jq 格式化
curl -s https://api.example.com/users | jq
# 使用 python
curl -s https://api.example.com/users | python -m json.tool
# 或用工具库的 JSON 格式化工具
3. 测量响应时间
# 详细时间统计
curl -w "DNS: %{time_namelookup}s\nConnect: %{time_connect}s\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n" \
-o /dev/null -s https://api.example.com/users
# 输出:
# DNS: 0.012s
# Connect: 0.035s
# TTFB: 0.120s
# Total: 0.125s
4. 排查 CORS 问题
浏览器报错:
Access to fetch at 'https://api.example.com' from origin 'https://app.example.com'
has been blocked by CORS policy
排查步骤:
1. 检查 OPTIONS 预检请求
curl -X OPTIONS -H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: POST" \
-i https://api.example.com/users
2. 检查响应头
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
5. 排查认证问题
401 Unauthorized 排查:
1. Token 是否过期?→ 用 JWT 解码工具查看 exp
2. Token 格式是否正确?→ 检查 Bearer 前缀
3. Token 是否发送?→ curl -v 检查请求头
403 Forbidden 排查:
1. 用户是否有权限?→ 检查用户角色
2. IP 是否在白名单?→ 检查服务端日志
3. 是否超过频率限制?→ 检查 429 状态码
API 测试最佳实践
1. 环境变量管理
# 使用环境变量存储敏感信息
export API_BASE="https://api.example.com"
export API_TOKEN="your-token"
curl -H "Authorization: Bearer $API_TOKEN" "$API_BASE/users"
2. 请求集合
#!/bin/bash
# api-test.sh
BASE="https://api.example.com"
TOKEN="Bearer $API_TOKEN"
HEADER="-H 'Content-Type: application/json' -H 'Authorization: $TOKEN'"
# 获取用户列表
get_users() { curl -s $HEADER "$BASE/users" | jq; }
# 创建用户
create_user() { curl -s -X POST $HEADER -d "$1" "$BASE/users" | jq; }
# 获取单个用户
get_user() { curl -s $HEADER "$BASE/users/$1" | jq; }
# 使用
get_users
create_user '{"name":"Bob"}'
get_user 1
3. 自动化测试
// 使用 fetch 写 API 测试
async function testApi() {
// 测试 GET
const listRes = await fetch('/api/users');
console.assert(listRes.status === 200, 'GET /users should return 200');
// 测试 POST
const createRes = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Test' }),
});
console.assert(createRes.status === 201, 'POST /users should return 201');
const created = await createRes.json();
console.assert(created.name === 'Test', 'Name should match');
}
常见问题
cURL 在 Windows 上引号不对?
Windows CMD 用双引号,PowerShell 有转义问题:
# PowerShell 中使用 cURL(其实是 Invoke-WebRequest 的别名)
# 使用 curl.exe 调用真正的 cURL
curl.exe -X POST https://api.example.com/users `
-H "Content-Type: application/json" `
-d '{\"name\": \"Alice\"}'
请求超时怎么排查?
1. DNS 解析慢?→ curl -w 查看 time_namelookup
2. 连接建立慢?→ curl -w 查看 time_connect
3. 服务端处理慢?→ curl -w 查看 time_starttransfer - time_connect
4. 响应传输慢?→ curl -w 查看 time_total - time_starttransfer
总结
API 调试是开发者的日常——掌握 cURL 命令、HTTP 状态码、认证方式和调试技巧,能快速定位接口问题。工具库的 cURL 转代码工具 和 JSON 格式化工具 是 API 调试的好搭档,帮你快速测试接口和查看响应。
#API测试#HTTP请求#cURL#接口调试#教程