实战
curl https://example.com # GET,输出到屏幕
curl -o page.html https://example.com # 存文件
curl -O https://example.com/file.zip # 用 URL 末段做文件名
curl -L https://example.com # 跟随重定向
curl -I https://example.com # 只看 headers(HEAD)
curl -s https://example.com # 静默
curl -v https://example.com # 看完整握手
POST 请求
# Form
curl -X POST -d "name=alice&age=30" https://api.example.com/users
# JSON
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"alice"}' \
https://api.example.com/users
# 从文件读 body
curl -X POST -d @data.json -H "Content-Type: application/json" ...
认证
# Basic
curl -u user:pass https://api.example.com
# Bearer
curl -H "Authorization: Bearer xxx" https://api.example.com
# Cookie
curl -b "session=abc" https://example.com
curl -c cookies.txt https://example.com # 保存
curl -b cookies.txt https://example.com # 用
调试(杀手锏)
看每一步耗时:
curl -w "@-" -o /dev/null -s https://example.com <<'EOF'
DNS: %{time_namelookup}s
TCP: %{time_connect}s
TLS: %{time_appconnect}s
TTFB: %{time_starttransfer}s
Total: %{time_total}s
HTTP: %{http_code}
Size: %{size_download} bytes
EOF
只看 status code:
curl -s -o /dev/null -w "%{http_code}" https://example.com
文件上传
# multipart/form-data
curl -F "file=@photo.jpg" https://api.example.com/upload
curl -F "name=alice" -F "avatar=@photo.jpg" https://api.example.com/profile
走代理
curl -x http://proxy.example.com:8080 https://example.com
curl --socks5 localhost:1080 https://example.com
配 jq 用(JSON 处理)
sudo apt install jq
# 取字段
curl -s https://api.github.com/users/torvalds | jq -r '.name'
# 取数组
curl -s https://api.github.com/users/torvalds/repos | jq -r '.[].name'
自签证书 / 调试 HTTPS
curl -k https://self-signed.example.com # 跳过证书校验(不安全)
curl --cacert /path/ca.crt https://example.com # 指定 CA
curl --tls-max 1.2 https://example.com # 限定 TLS 版本
常用参数速查
| 参数 | 含义 |
|---|---|
-X METHOD |
HTTP 方法(GET/POST/PUT/DELETE) |
-d DATA |
请求体 |
-H "Header: val" |
自定义 header |
-o FILE |
存文件 |
-O |
用 URL 文件名 |
-L |
跟随重定向 |
-I |
HEAD 请求 |
-s |
静默 |
-v |
verbose |
-k |
跳过证书校验 |
-u USER:PASS |
Basic Auth |
-A "UA" |
自定义 User-Agent |
-x PROXY |
HTTP 代理 |
-w FORMAT |
输出格式(前面 timing) |
坑
- curl 默认不跟随重定向——
-L才跟 - 复杂 JSON 体里
'要小心 shell 转义——用-d @file.json从文件读最稳 -X POST时如果没-d,仍然是 GET——必须有数据 / 或加-X POST后用-d ''