目录
简介
curl(CommandLine URL)是一个强大的命令行工具,用于在客户端和服务器之间传输数据。它支持多种协议,包括 HTTP、HTTPS、FTP、FTPS、SCP、SFTP、TFTP、DICT、TELNET、LDAP 等。
主要特点
- 支持多种网络协议
- 支持 Cookie、认证、代理
- 支持文件上传和下载
- 支持 SSL/TLS
- 跨平台支持
基本语法
curl [options] [URL...]
常用参数详解
1. 基础参数
-X, --request <method>
指定 HTTP 请求方法(GET、POST、PUT、DELETE 等)
curl -X GET https://api.example.com/users
curl -X POST https://api.example.com/users
curl -X PUT https://api.example.com/users/1
curl -X DELETE https://api.example.com/users/1
-d, --data <data>
发送 POST 请求数据
curl -X POST -d "name=John&age=30" https://api.example.com/users
curl -X POST -d '{"name":"John","age":30}' https://api.example.com/users
-H, --header <header>
添加自定义请求头
curl -H "Content-Type: application/json" https://api.example.com
curl -H "Authorization: Bearer token123" https://api.example.com
curl -H "User-Agent: MyApp/1.0" https://api.example.com
-o, --output <file>
将响应保存到指定文件
curl -o output.html https://www.example.com
curl -o image.jpg https://example.com/image.jpg
-O, --remote-name
使用 URL 中的文件名保存
curl -O https://example.com/file.zip
2. 认证参数
-u, --user <user:password>
HTTP 基本认证
curl -u username:password https://api.example.com
curl -u username https://api.example.com # 会提示输入密码
--basic
强制使用 HTTP Basic 认证
curl --basic -u username: password https://api.example.com
--digest
使用 HTTP Digest 认证
curl --digest -u username:password https://api.example.com
3. Cookie 相关
-b, --cookie <data>
发送 Cookie
curl -b "session=abc123" https://api.example.com
curl -b cookies.txt https://api.example.com
-c, --cookie-jar <file>
保存响应的 Cookie 到文件
curl -c cookies.txt https://api.example.com/login
4. 调试和输出参数
-v, --verbose
显示详细的请求和响应信息
curl -v https://api.example.com
-i, --include
在输出中包含 HTTP 响应头
curl -i https://api.example.com
-I, --head
仅获取 HTTP 头信息
curl -I https://www.example.com
-s, --silent
静默模式,不显示进度条
curl -s https://api.example.com
-S, --show-error
与 -s 一起使用时显示错误信息
curl -sS https://api.example.com
5. 下载相关
-C, --continue-at <offset>
断点续传
curl -C - -O https://example.com/largefile.zip
-L, --location
跟随重定向
curl -L https://example.com
--limit-rate <speed>
限制传输速度
curl --limit-rate 100K -O https://example.com/file.zip
-#, --progress-bar
显示进度条
curl -# -O https://example.com/file.zip
6. 代理相关
-x, --proxy <[protocol://][user:password@]host[: port]>
使用代理服务器
curl -x http://proxy.example.com:8080 https://api.example.com
curl -x socks5://127.0.0.1:1080 https://api.example.com
--noproxy <hosts>
不使用代理的主机列表
curl --noproxy localhost,127.0.0.1 -x http://proxy:8080 https://api.example.com
7. SSL/TLS 相关
-k, --insecure
允许不安全的 SSL 连接
curl -k https://self-signed.example.com
--cacert <file>
指定 CA 证书
curl --cacert ca-bundle.crt https://api.example.com
--cert <certificate[: password]>
使用客户端证书
curl --cert mycert.pem https://api.example.com
8. 超时参数
--connect-timeout <seconds>
连接超时时间
curl --connect-timeout 10 https://api.example.com
--max-time <seconds>
最大执行时间
curl --max-time 30 https://api.example.com
9. 其他实用参数
-A, --user-agent <name>
设置 User-Agent
curl -A "Mozilla/5.0" https://www.example.com
-e, --referer <URL>
设置 Referer
curl -e "https://google.com" https://www.example.com
-w, --write-out <format>
自定义输出格式
curl -w "\nHTTP Code: %{http_code}\n" https://api.example.com
curl -w "Time: %{time_total}s\n" https://api.example.com
-F, --form <name=content>
提交表单(multipart/form-data)
curl -F "file=@/path/to/file. txt" https://api.example.com/upload
curl -F "name=John" -F "email=john@example.com" https://api.example.com
实战场景
场景 1: RESTful API 测试
GET 请求
# 获取���户列表
curl -X GET https://api.example.com/users
# 获取单个用户
curl -X GET https://api.example.com/users/123
# 带查询参数
curl -X GET "https://api.example.com/users?page=1&limit=10"
POST 请求(JSON 数据)
# 创建用户
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{
"name": "张三",
"email": "zhangsan@example.com",
"age": 28
}'
# 使用文件中的 JSON 数据
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d @user.json
PUT 请求(更新资源)
curl -X PUT https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your_token_here" \
-d '{
"name": "李四",
"email": "lisi@example.com"
}'
DELETE 请求
curl -X DELETE https://api.example.com/users/123 \
-H "Authorization: Bearer your_token_here"
场景 2: 文件上传下载
下载文件
# 基本下载
curl -O https://example.com/file.zip
# 重命名下载
curl -o myfile.zip https://example.com/file.zip
# 断点续传
curl -C - -O https://example.com/largefile.iso
# 批量下载
curl -O https://example.com/file[1-10].jpg
上传文件
# 上传单个文件
curl -F "file=@/path/to/document.pdf" https://api.example.com/upload
# 上传多个文件
curl -F "file1=@image1.jpg" -F "file2=@image2.jpg" https://api.example.com/upload
# 带额外参数上传
curl -F "file=@document.pdf" \
-F "description=Important document" \
-F "category=reports" \
https://api.example.com/upload
场景 3: 网站健康检查
# 检查网站响应状态
curl -I -s https://www.example.com | grep HTTP
# 检查响应时间
curl -w "\nTotal time: %{time_total}s\n" -o /dev/null -s https://www.example.com
# 完整的性能监控
curl -w "\n\
DNS lookup time: %{time_namelookup}s\n\
TCP connect time: %{time_connect}s\n\
SSL handshake time: %{time_appconnect}s\n\
Transfer start time: %{time_starttransfer}s\n\
Total time: %{time_total}s\n\
HTTP code: %{http_code}\n\
Size downloaded: %{size_download} bytes\n" \
-o /dev/null -s https://www.example.com
场景 4: OAuth 2.0 认证
# 获取访问令牌
curl -X POST https://oauth.example.com/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials" \
-d "client_id=your_client_id" \
-d "client_secret=your_client_secret"
# 使用访问令牌调用 API
TOKEN="your_access_token"
curl -X GET https://api.example.com/protected \
-H "Authorization: Bearer $TOKEN"
场景 5: GraphQL 查询
# GraphQL 查询
curl -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{
"query": "{ users { id name email } }"
}'
# 带变量的 GraphQL 查询
curl -X POST https://api.example.com/graphql \
-H "Content-Type: application/json" \
-d '{
"query": "query GetUser($id: ID!) { user(id: $id) { name email } }",
"variables": { "id": "123" }
}'
场景 6: Webhook 测试
# 模拟 GitHub Webhook
curl -X POST https://your-server.com/webhook \
-H "Content-Type: application/json" \
-H "X-GitHub-Event: push" \
-d '{
"ref": "refs/heads/main",
"commits": [
{
"id": "abc123",
"message": "Update README"
}
]
}'
场景 7: 爬虫和数据抓取
# 抓取网页内容
curl -s https://www.example.com | grep -o '<title>.*</title>'
# 模拟浏览器访问
curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" \
-H "Accept-Language: zh-CN,zh;q=0.9" \
-e "https://google.com" \
https://www.example.com
# 保存 Cookie 并在后续请求中使用
curl -c cookies.txt -d "username=user&password=pass" https://example.com/login
curl -b cookies.txt https://example.com/profile
场景 8: FTP 操作
# 下载文件
curl -u username:password ftp://ftp.example.com/file.txt -o file.txt
# 上传文件
curl -u username:password -T localfile. txt ftp://ftp.example.com/
# 列出目录
curl -u username:password ftp://ftp.example.com/directory/
场景 9: 并发请求和性能测试
# 使用 GNU Parallel 进行并发测试
seq 1 100 | parallel -j 10 curl -s -o /dev/null -w "%{http_code}\n" https://api.example.com
# 简单的循环测试
for i in {1.. 10}; do
curl -s -o /dev/null -w "Request $i: %{http_code} - %{time_total}s\n" \
https://api.example.com
done
场景 10: Docker Registry API
# 获取镜像标签列表
curl -X GET https://registry.example.com/v2/myapp/tags/list
# 带认证的请求
curl -X GET https://registry.example.com/v2/_catalog \
-u username:password
高级技巧
1. 使用配置文件
创建 .curlrc 文件来保存常用配置:
# ~/. curlrc
user-agent = "MyCustomUserAgent/1.0"
referer = "https://www.google.com"
connect-timeout = 10
max-time = 30
2. JSON 数据美化输出
# 使用 jq 美化 JSON 输出
curl -s https://api.example.com/users | jq '.'
# 提取特定字段
curl -s https://api.example.com/users | jq '.[]. name'
3. 循环处理多个 URL
# 从文件读取 URL 列表
while IFS= read -r url; do
curl -s -o /dev/null -w "$url: %{http_code}\n" "$url"
done < urls.txt
4. 条件请求(If-Modified-Since)
curl -H "If-Modified-Since: Wed, 01 Jan 2026 00:00:00 GMT" \
https://api.example.com/data
5. 发送原始 HTTP 请求
# 从文件发送完整的 HTTP 请求
curl --data-binary @request.txt \
--header "Content-Type: application/x-www-form-urlencoded" \
https://api.example.com
6. 使用环境变量
# 设置环境变量
export API_TOKEN="your_token_here"
export API_BASE="https://api.example.com"
# 在 curl 中使用
curl -H "Authorization: Bearer $API_TOKEN" "$API_BASE/users"
7. 调试 DNS 解析
# 指定 DNS 服务器
curl --dns-servers 8.8.8.8 https://www.example.com
# 指定 IP 地址解析
curl --resolve example.com:443: 1.2.3.4 https://example.com
常见问题
1. SSL 证书验证失败
# 临时解决(不推荐用于生产环境)
curl -k https://self-signed.example.com
# 正确做法:指定 CA 证书
curl --cacert /path/to/ca-bundle.crt https://api.example.com
2. 处理特殊字符
# URL 编码
curl "https://api.example.com/search?q=hello%20world"
# 使用 --data-urlencode
curl -G https://api.example.com/search \
--data-urlencode "q=hello world" \
--data-urlencode "type=all"
3. 调试重定向问题
# 查看重定向链
curl -L -v https://short.url/abc 2>&1 | grep -i location
4. 超时问题
# 设置合理的超时时间
curl --connect-timeout 10 --max-time 60 https://api.example.com
5. 保存完整的调试信息
# 保存详细日志
curl -v https://api.example.com 2>&1 | tee curl-debug.log
实用脚本示例
API 健康检查脚本
#!/bin/bash
# health-check.sh
ENDPOINTS=(
"https://api.example.com/health"
"https://api.example.com/status"
"https://api.example.com/ping"
)
for endpoint in "${ENDPOINTS[@]}"; do
http_code=$(curl -s -o /dev/null -w "%{http_code}" "$endpoint")
response_time=$(curl -s -o /dev/null -w "%{time_total}" "$endpoint")
if [ "$http_code" -eq 200 ]; then
echo "✓ $endpoint - OK (${response_time}s)"
else
echo "✗ $endpoint - FAILED (HTTP $http_code)"
fi
done
批量文件下载脚本
#!/bin/bash
# batch-download.sh
BASE_URL="https://example.com/files"
FILES=("file1.zip" "file2.zip" "file3.zip")
for file in "${FILES[@]}"; do
echo "Downloading $file..."
curl -# -C - -O "$BASE_URL/$file"
if [ $? -eq 0 ]; then
echo "✓ $file downloaded successfully"
else
echo "✗ Failed to download $file"
fi
done
API 性能监控脚本
#!/bin/bash
# api-monitor.sh
API_URL="https://api.example.com/endpoint"
ITERATIONS=10
total_time=0
for i in $(seq 1 $ITERATIONS); do
response_time=$(curl -s -o /dev/null -w "%{time_total}" "$API_URL")
total_time=$(echo "$total_time + $response_time" | bc)
echo "Request $i: ${response_time}s"
done
average=$(echo "scale=3; $total_time / $ITERATIONS" | bc)
echo "Average response time: ${average}s"
参考资源
总结
curl 是一个功能强大且灵活的命令行工具,掌握其使用方法对于 Web 开发、API 测试、系统管理等工作都非常重要。本文档涵盖了 curl 的常用参数和实战场景,希望能帮助您更高效地使用这个工具。
记住以下几点:
- 使用
-v 进行调试
- 使用
-s 和 -S 进行脚本化
- 合理设置超时参数
- 注意安全性(避免在命令行中暴露敏感信息)
- 善用配置文件和环境变量
Happy curling! 🚀