curl 是一个强大的命令行工具,用于传输数据,支持多种协议(HTTP、HTTPS、FTP 等)。以下是 curl 的基本使用方法和常见示例。
基本语法
1
| curl [options] [URL...]
|
常用选项
| 选项 | 描述 |
|---|
-X | 指定 HTTP 请求方法 (GET, POST, PUT, DELETE 等) |
-H | 添加请求头 |
-d | 发送 POST 请求数据 |
-F | 发送表单数据 (multipart/form-data) |
-G | 将 -d 数据作为 GET 请求的查询参数 |
-o | 将输出保存到文件 |
-O | 将输出保存到文件,使用远程文件名 |
-L | 跟随重定向 |
-v | 显示详细输出 (verbose) |
-u | 指定用户名和密码 |
-A | 设置 User-Agent |
-k | 允许不安全的 SSL 连接 |
-I | 只获取响应头 |
-s | 静默模式 (不显示进度或错误信息) |
--data-urlencode | URL 编码 POST 数据 |
常见用法示例
1. 发送 GET 请求
1
| curl https://example.com
|
2. 发送 POST 请求
1
| curl -X POST https://example.com/api -d 'name=value'
|
3. 发送 JSON 数据
1
2
3
| curl -X POST https://example.com/api \
-H "Content-Type: application/json" \
-d '{"key1":"value1", "key2":"value2"}'
|
4. 发送表单数据
1
2
3
| curl -X POST https://example.com/form \
-d 'username=admin' \
-d 'password=123456'
|
5. 上传文件
1
2
| curl -X POST https://example.com/upload \
-F "file=@/path/to/file.txt"
|
6. 设置请求头
1
2
3
| curl -H "Authorization: Bearer token" \
-H "Content-Type: application/json" \
https://example.com/api
|
7. 下载文件
1
| curl -O https://example.com/file.zip
|
8. 跟随重定向
1
| curl -L https://example.com/redirect
|
9. 使用基本认证
1
| curl -u username:password https://example.com
|
10. 保存 cookie 并发送
1
2
3
4
5
| # 保存 cookie
curl -c cookies.txt https://example.com/login -d "user=name&pass=123"
# 使用 cookie
curl -b cookies.txt https://example.com/dashboard
|
11. 测试 API 响应时间
1
| curl -o /dev/null -s -w 'Total: %{time_total}s\n' https://example.com
|
12. 限制下载速度
1
| curl --limit-rate 100K -O https://example.com/largefile.zip
|
高级用法
发送多部分请求
1
2
3
| curl -X POST https://example.com/upload \
-F "file=@image.jpg" \
-F "description=My image"
|
使用代理
1
| curl -x http://proxy.example.com:8080 https://example.com
|
调试请求
1
| curl -v https://example.com
|
只获取响应头
1
| curl -I https://example.com
|
使用自定义 User-Agent
1
| curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" https://example.com
|
注意事项
- 在脚本中使用 curl 时,考虑添加
-s 或 -sS 选项(-S 显示错误) - 处理 JSON 数据时,可以使用
jq 工具进行格式化 - 对于复杂的 API 调用,考虑将请求保存为文件并使用
-K 选项 - 在 Windows 上,使用双引号
" 而不是单引号 '