curl:被低估的调试利器
每个开发者都用过 curl,但大多数人只停留在 curl https://api.example.com 的层面。实际上,curl 是一个功能极其强大的网络调试工具——从性能分析到认证调试,从 Cookie 管理到断点续传,它几乎能覆盖 HTTP 调试的方方面面。本文分享 10 个让你效率翻倍的 curl 高级技巧。
技巧1:用 -w 做性能分析
你知道吗?curl 可以输出请求各阶段的耗时,效果堪比专业的网络性能分析工具。
1
2
3
4
5
6
7
8
9
|
curl -o /dev/null -s -w "\
DNS解析: %{time_namelookup}s\n\
TCP连接: %{time_connect}s\n\
TLS握手: %{time_appconnect}s\n\
首字节到达: %{time_starttransfer}s\n\
总耗时: %{time_total}s\n\
HTTP状态码: %{http_code}\n\
下载大小: %{size_download} bytes\n" \
https://api.github.com/users/torvalds
|
输出示例:
1
2
3
4
5
6
7
|
DNS解析: 0.012s
TCP连接: 0.045s
TLS握手: 0.120s
首字节到达: 0.180s
总耗时: 0.210s
HTTP状态码: 200
下载大小: 1245 bytes
|
当你排查"接口慢"的问题时,这段输出能帮你快速定位瓶颈——是 DNS 解析慢,还是 TLS 握手耗时,还是服务端处理(首字节到达 - TLS握手)太慢?
技巧2:跟随重定向并查看完整链路
API 接口经常返回 301/302 重定向,加 -L 跟随,加 -v 查看完整过程:
1
|
curl -L -v https://example.com/redirect 2>&1
|
如果你想看每一跳的请求和响应头,而不只是最终结果:
1
|
curl -L -v --trace-ascii - https://httpbin.org/redirect/2 2>&1 | head -50
|
技巧3:发送 JSON POST 请求的正确姿势
很多人发送 JSON 时会忘记设 Content-Type,导致服务端解析失败:
1
2
3
4
5
6
7
8
|
# ❌ 错误:缺少 Content-Type
curl -X POST https://api.example.com/users \
-d '{"name":"张三","email":"[email protected]"}'
# ✅ 正确:显式声明 JSON
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name":"张三","email":"[email protected]"}'
|
更优雅的方式——从文件读取 JSON 请求体,避免 shell 转义地狱:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# 准备请求体文件
cat > payload.json << 'EOF'
{
"name": "张三",
"email": "[email protected]",
"roles": ["admin", "editor"]
}
EOF
# 用 @ 语法从文件读取
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d @payload.json
|
技巧4:一行命令搞定多种认证
Basic Auth(用户名密码):
1
|
curl -u username:password https://api.example.com/data
|
Bearer Token(JWT/OAuth):
1
2
|
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
https://api.example.com/protected
|
从环境变量读取 token,避免硬编码到命令历史:
1
2
|
curl -H "Authorization: Bearer $API_TOKEN" \
https://api.example.com/protected
|
技巧5:Cookie 管理与会话保持
模拟登录后保持会话是常见需求。用 -c 保存 Cookie,-b 读取 Cookie:
1
2
3
4
5
6
7
|
# 第一步:登录并保存 Cookie
curl -c cookies.txt -X POST https://api.example.com/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"secret"}'
# 第二步:带着 Cookie 访问需认证的接口
curl -b cookies.txt https://api.example.com/dashboard
|
cookies.txt 是标准的 Netscape Cookie 格式,可以直接查看和编辑。
技巧6:只看响应头,不看响应体
调试时经常只需要看响应头,不需要下载整个响应体:
1
2
3
4
5
6
7
8
|
# 只获取响应头(HEAD 请求)
curl -I https://api.example.com/users
# 或者在 GET 请求中把响应头导出到文件
curl -D headers.txt -o body.json https://api.example.com/users
# 同时查看请求头和响应头
curl -v -o /dev/null https://api.example.com/users 2>&1 | grep -E "^< |^> "
|
技巧7:下载文件与断点续传
下载大文件时,断点续传能省去重新下载的时间:
1
2
3
4
5
6
7
8
|
# 普通下载
curl -O https://example.com/large-file.zip
# 断点续传(从中断处继续)
curl -C - -O https://example.com/large-file.zip
# 下载并显示进度条
curl -# -o video.mp4 https://example.com/video.mp4
|
-C - 中的 - 表示自动检测已下载的大小,从断点继续。
技巧8:超时与重试控制
线上环境调用 API,必须设超时,避免请求挂死:
1
2
3
4
5
6
7
8
|
# 连接超时5秒,总超时10秒
curl --connect-timeout 5 --max-time 10 https://api.example.com/data
# 失败自动重试3次,每次间隔1秒
curl --retry 3 --retry-delay 1 \
--retry-connrefused \
--max-time 30 \
https://api.example.com/data
|
--retry-connrefused 是关键参数——默认情况下 curl 只对 HTTP 5xx 错误重试,加上这个参数后连接被拒绝也会重试,非常适合调试间歇性不可用的服务。
技巧9:模拟慢速网络
前端调试时,需要模拟慢速网络看加载效果:
1
2
3
4
5
6
7
|
# 限制下载速度为 10KB/s
curl --limit-rate 10k -O https://example.com/large-file.zip
# 限制上传速度为 100KB/s
curl --limit-rate 100k -X POST \
-F "[email protected]" \
https://api.example.com/upload
|
技巧10:批量请求与并发
用 shell 脚本配合 curl 做批量请求,测试接口的并发表现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#!/bin/bash
# batch_curl.sh — 并发请求测试
URL="https://api.example.com/data"
COUNT=10
echo "并发发送 $COUNT 个请求..."
for i in $(seq 1 $COUNT); do
curl -s -o /dev/null -w "请求#$i: %{http_code} %{time_total}s\n" \
"$URL" &
done
wait
echo "全部完成"
|
执行 bash batch_curl.sh,你会看到 10 个请求并发发出,各自的响应码和耗时一目了然。
组合技:一键API健康检查
把上面的技巧组合起来,写一个实用的 API 健康检查脚本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#!/bin/bash
# health_check.sh — API 健康检查
URL="${1:-https://api.example.com/health}"
TIMEOUT=10
echo "检查目标: $URL"
echo "--------------------------------"
response=$(curl -s -o /tmp/health_body.txt \
-w "%{http_code} %{time_total}" \
--max-time $TIMEOUT \
"$URL")
http_code=$(echo "$response" | awk '{print $1}')
total_time=$(echo "$response" | awk '{print $2}')
if [ "$http_code" = "200" ]; then
echo "✅ 健康 (HTTP $http_code, 耗时 ${total_time}s)"
echo "响应: $(cat /tmp/health_body.txt | head -c 200)"
else
echo "❌ 异常 (HTTP $http_code, 耗时 ${total_time}s)"
exit 1
fi
|
用法:bash health_check.sh https://your-api.com/health
总结
curl 远不止是一个"发 HTTP 请求的工具"。掌握这些高级技巧后,你可以在不安装任何额外软件的情况下,完成性能分析、认证调试、会话管理、断点续传、并发测试等工作。建议把本文中的命令保存为 snippet,日常开发中随用随取。
下次遇到 HTTP 调试问题,先想想:能不能用 curl 一行命令搞定?