关于 curl-http
curl-http 是面向开发者的 curl 和 HTTPie 命令行参考技能,适用于发送 HTTP 请求和测试 API。示例涵盖请求构造、响应检查、文件传输、故障排查及常见命令陷阱。
主要功能
- 01HTTP 方法、标头和请求体示例
- 02身份验证、Cookie 和 TLS 选项
- 03检查响应并测量请求耗时
- 04下载、重试、限速和代理
- 05对照 curl 与 HTTPie 语法
适用场景
- 01构造 JSON API 请求
- 02排查响应标头和耗时问题
- 03下载或续传大型文件
- 04为任务选择 curl 或 HTTPie 语法
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ 1mangesh1/ dev-skills-collection --skill curl-http安装后在 Claude Code 中输入/curl-http确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
examples/curl-requests.jsonreferences/http-guide.mdhttp-reference.mdscripts/api-tester.shhttp-debug.shresponse-analyzer.sh详细介绍
curl 和 HTTPie 参考
HTTP 方法
# GET
curl https://api.example.com/users
curl -s https://api.example.com/users # suppress progress meter
curl -i https://api.example.com/users # include response headers
curl -I https://api.example.com/users # HEAD request (headers only)
# POST (JSON body)
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"[email protected]"}'
curl -X POST https://api.example.com/users -H "Content-Type: application/json" -d @payload.json
# PUT
curl -X PUT https://api.example.com/users/42 \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"[email protected]"}'
# PATCH
curl -X PATCH https://api.example.com/users/42 \
-H "Content-Type: application/json" -d '{"status":"active"}'
# DELETE
curl -X DELETE https://api.example.com/users/42
curl -X DELETE https://api.example.com/users/42 -H "Content-Type: application/json" -d '{"reason":"duplicate"}'
标头
curl -H "X-Request-ID: abc123" https://api.example.com # single header
curl -H "Accept: application/json" -H "Content-Type: application/json" \
-H "X-API-Key: key123" https://api.example.com # multiple
curl -H "User-Agent: my-script/1.0" https://api.example.com # override default
curl -H "Accept:" https://api.example.com # remove a default header
请求正文
# JSON
curl -X POST https://api.example.com/data -H "Content-Type: application/json" \
-d '{"key":"value","count":10}'
# URL-encoded form data
curl -X POST https://api.example.com/login -d "username=alice&password=secret"
curl -X POST https://api.example.com/search --data-urlencode "q=hello world&limit=10"
# Multipart file upload
curl -X POST https://api.example.com/upload -F "[email protected]" -F "description=Quarterly report"
curl -X POST https://api.example.com/upload -F "[email protected];type=image/png"
# Raw binary upload
curl -X POST https://api.example.com/upload --data-binary @archive.tar.gz \
-H "Content-Type: application/octet-stream"
身份验证
# Basic auth
curl -u alice:secretpass https://api.example.com/me
curl -H "Authorization: Basic $(echo -n alice:secretpass | base64)" https://api.example.com/me
# Bearer token
curl -H "Authorization: Bearer eyJhbGciOi..." https://api.example.com/me
# API key (as header or query parameter)
curl -H "X-API-Key: abc123" https://api.example.com/data
curl "https://api.example.com/data?api_key=abc123"
# OAuth 2.0 client credentials flow
TOKEN=$(curl -s -X POST https://auth.example.com/oauth/token \
-d "grant_type=client_credentials" \
-d "client_id=CLIENT_ID" \
-d "client_secret=CLIENT_SECRET" | jq -r '.access_token')
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/resource
响应处理
# Extract status code
curl -s -o /dev/null -w "%{http_code}" https://api.example.com
# Headers only / headers with body
curl -I https://api.example.com
curl -i https://api.example.com
# Save response to file
curl -o response.json https://api.example.com/data
curl -O https://cdn.example.com/file.tar.gz # keep remote filename
curl -D headers.txt -o body.json https://api.example.com/data # separate files
# Follow redirects
curl -L https://short.url/abc
curl -L --max-redirs 5 https://short.url/abc
# Check success in scripts
if curl -s -f -o /dev/null https://api.example.com/health; then
echo "Service is up"
fi
# Pretty-print JSON
curl -s https://api.example.com/data | jq .
curl -s https://api.example.com/data | python3 -m json.tool
详细和调试模式
curl -v https://api.example.com # request/response headers + TLS handshake
curl -v https://api.example.com 2>debug.log # verbose output to file
curl --trace - https://api.example.com # full hex trace to stderr
curl --trace trace.log --trace-time https://api.example.com # trace with timestamps
curl -s -D - -o /dev/null https://api.example.com # headers only (less noisy than -v)
耗时分解
# Single metric
curl -s -o /dev/null -w "Total: %{time_total}s\n" https://api.example.com
# Full breakdown (DNS lookup, TCP connect, TLS handshake, TTFB, total)
curl -s -o /dev/null -w "\
DNS: %{time_namelookup}s\n\
Connect: %{time_connect}s\n\
TLS: %{time_appconnect}s\n\
TTFB: %{time_starttransfer}s\n\
Total: %{time_total}s\n\
Size: %{size_download} bytes\n\
Speed: %{speed_download} bytes/s\n" https://api.example.com
# Reusable: save the format string to a file and reference with -w @curl-timing.txt
Cookie
curl -b "session=abc123" https://api.example.com # send a cookie
curl -c cookies.txt https://api.example.com/login -d "user=alice&pass=s" # save cookies
curl -b cookies.txt https://api.example.com/dashboard # load cookies
curl -b cookies.txt -c cookies.txt https://api.example.com/action # cookie jar
SSL/TLS 选项
curl -k https://self-signed.example.com # skip cert verification
curl --cacert /path/to/ca-bundle.crt https://api.example.com # custom CA bundle
curl --cert client.pem --key client-key.pem https://api.example.com # client certificate
curl --tlsv1.2 https://api.example.com # force TLS 1.2
curl --tlsv1.3 https://api.example.com # force TLS 1.3
代理设置
curl -x http://proxy.example.com:8080 https://api.example.com # HTTP proxy
curl --socks5 127.0.0.1:1080 https://api.example.com # SOCKS5 proxy
curl --socks5-hostname 127.0.0.1:1080 https://api.example.com # DNS via proxy
curl -x http://user:[email protected]:8080 https://api.example.com # proxy with auth
curl --noproxy "localhost,127.0.0.1,.internal" https://api.example.com # bypass proxy
速率限制和重试
curl --retry 5 https://api.example.com # retry on transient errors
curl --retry 5 --retry-delay 3 https://api.example.com # 3s between retries
curl --retry 5 --retry-all-errors https://api.example.com # retry all errors (7.71+)
curl --limit-rate 100K https://cdn.example.com/large.zip -o file.zip # throttle transfer
curl --connect-timeout 5 --max-time 30 https://api.example.com # timeouts
下载文件
curl -O https://cdn.example.com/archive.tar.gz # download with progress
curl -sO https://cdn.example.com/archive.tar.gz # download silently
curl -C - -O https://cdn.example.com/large-file.iso # resume interrupted
curl -O https://cdn.example.com/a.zip -O https://cdn.example.com/b.zip # multiple files
curl -o local-name.tar.gz https://cdn.example.com/archive.tar.gz # rename on save
API 测试模式
# CRUD cycle
ID=$(curl -s -X POST https://api.example.com/items \
-H "Content-Type: application/json" -d '{"name":"test"}' | jq -r '.id')
curl -s https://api.example.com/items/$ID | jq .
curl -s -X PATCH https://api.example.com/items/$ID \
-H "Content-Type: application/json" -d '{"name":"updated"}' | jq .
curl -s -X DELETE https://api.example.com/items/$ID
# GraphQL
curl -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{"query":"{ users { id name email } }"}'
# Webhook testing
curl -X POST https://your-app.example.com/webhooks \
-H "Content-Type: application/json" -H "X-Webhook-Secret: secret123" \
-d '{"event":"order.created","data":{"id":1}}'
# Health check script
for endpoint in /health /ready /metrics; do
code=$(curl -s -o /dev/null -w "%{http_code}" "https://api.example.com${endpoint}")
echo "${endpoint}: ${code}"
done
将 curl 转换为代码
# Generate C source reproducing the request via libcurl
curl --libcurl generated.c -X POST https://api.example.com/data \
-H "Content-Type: application/json" -d '{"key":"value"}'
# Third-party converters (curlconverter.com) support Python, JS, Go, PHP, etc.
# npm install -g curlconverter
# curlconverter --language python 'curl -X POST ...'
HTTPie 作为替代方案
HTTPie(http / https 命令)为常见任务提供了更易读的语法。
# GET
http https://api.example.com/users # colored, formatted output
http -b https://api.example.com/users # body only
http -h https://api.example.com/users # headers only
# POST JSON (default content type)
http POST https://api.example.com/users name=Alice [email protected]
http POST https://api.example.com/users name=Alice age:=30 active:=true tags:='["a","b"]'
# Auth
http -a alice:secret https://api.example.com/me # basic
http https://api.example.com/me "Authorization:Bearer tok" # bearer
# File upload and download
http --form POST https://api.example.com/upload [email protected]
http --download https://cdn.example.com/archive.tar.gz
对比表
| 操作 | curl | HTTPie |
|---|---|---|
| 带标头的 GET | curl -i URL | http URL |
| POST JSON | curl -X POST -H C-T:json -d '{}' | http POST URL key=val |
| Bearer 身份验证 | curl -H "Authorization: Bearer T" | http URL Authorization:Bearer\ T |
| 下载文件 | curl -O URL | http --download URL |
| 表单上传 | curl -F "f=@file" | http --form POST URL f@file |
常见注意事项
引号
# Unix: wrap JSON in single quotes
curl -d '{"key":"value"}' https://api.example.com
# Windows cmd.exe: escape inner quotes or use a file
curl -d "{\"key\":\"value\"}" https://api.example.com
curl -d @payload.json https://api.example.com
Windows 与 Unix
cmd.exe不支持单引号;请使用双引号,并对其中的引号进行转义。- PowerShell 需要使用反引号转义或 here-string 来处理 JSON 正文。
- 续行符:Unix 上使用
\,Windowscmd.exe上使用^。
其他易错点
- 服务器返回 301/302 重定向时忘记使用
-L。 - 将
-X GET与-d一起使用——curl 会发送正文,但有些服务器会忽略 GET 请求中的正文。 - 未对查询参数进行 URL 编码;请使用
--data-urlencode或--url-query(curl 7.87+)。 - 在 Windows 上,
-o /dev/null应改为-o NUL。 - 未使用
--output -就通过管道传输二进制输出,可能会损坏终端显示。
评论
支持 Markdown