curl 常用请求与调试速查
常用命令
curl https://example.com/
curl -I https://example.com/
curl -v https://example.com/
curl -fsSL -o file.tar.gz https://example.com/file.tar.gz
curl -X POST -H 'Content-Type: application/json' \
-d '{"name":"app"}' https://api.example.com/items
curl -u user:pass https://api.example.com/
curl -H 'Authorization: Bearer $TOKEN' https://api.example.com/
curl -b cookies.txt -c cookies.txt https://example.com/
curl -L https://example.com/redirect
curl --max-time 10 --connect-timeout 5 https://example.com/
curl -w '\ncode=%{http_code} total=%{time_total}\n' -o /dev/null -s https://example.com/
curl --retry 3 --retry-delay 2 https://example.com/
curl --resolve example.com:443:10.0.0.10 https://example.com/
常用选项
| 选项 |
含义 |
-X |
HTTP 方法 |
-H |
请求头 |
-d |
请求体 |
-F |
表单/文件上传 |
-u |
Basic Auth |
-b/-c |
读取/保存 cookie |
-L |
跟随重定向 |
-k |
跳过证书校验(慎用) |
--cacert |
指定 CA |
-o/-O |
输出文件 |
-s/-S |
静默/显示错误 |
-w |
输出统计 |
--retry |
重试 |
场景速查
| 目的 |
写法 |
| 只看状态码 |
curl -s -o /dev/null -w '%{http_code}' URL |
| 测各阶段耗时 |
-w '%{time_namelookup} %{time_connect} %{time_starttransfer} %{time_total}' |
| 下载断点续传 |
curl -C - -O URL |
| 上传文件 |
curl -F 'file=@app.tar.gz' URL |
| 指定 Host |
curl -H 'Host: example.com' http://IP/ |
| 忽略代理 |
curl --noproxy '*' URL |
易错点
- 不加
-f 时,HTTP 4xx/5xx 仍返回成功退出码;脚本里要加 -f。
- 默认输出到 stdout;二进制内容会刷屏,记得
-o。
-k 只用于排障,不要在生产脚本里跳过证书校验。
- 代理环境变量会影响 curl;用
--noproxy 或显式 -x。
-d 默认使用 application/x-www-form-urlencoded;JSON 要加 header。
- 重定向默认不跟随;需要
-L,但要注意跨域/认证头。
- 超时要区分连接超时和总超时。
相关命令
wget — 下载工具
openssl — TLS 排查
jq — JSON 处理