curl 是支持多种协议的网络请求工具,是 API 测试和文件下载的首选。
curl 支持 HTTP、HTTPS、FTP、SFTP 等多种协议,可以发送请求、下载/上传文件、测试 API。它是命令行中最通用的网络工具。支持自定义请求头、Cookie、认证、代理等。
示例 1:GET 请求
curl https://api.example.com/users
示例 2:查看响应头
curl -I https://example.com
HTTP/2 200
server: nginx/1.24.0
content-type: text/html; charset=utf-8
date: Mon, 19 Aug 2024 10:30:00 GMT
示例 3:POST 请求发送 JSON
curl -X POST -H "Content-Type: application/json" \
-d '{"name": "alice", "email": "alice@example.com"}' \
https://api.example.com/users
示例 4:下载文件并保存
curl -o package.tar.gz https://example.com/package.tar.gz
示例 5:跟随重定向
curl -L https://example.com/redirect
示例 6:发送认证头
curl -H "Authorization: Bearer TOKEN123" https://api.example.com/me
示例 7:使用基本认证
curl -u username:password https://api.example.com/secure
示例 8:上传文件
curl -F "file=@/path/to/file.txt" https://upload.example.com/
示例 9:保存 Cookie 并使用
curl -c cookies.txt -d "username=admin&password=secret" https://example.com/login
curl -b cookies.txt https://example.com/dashboard
示例 10:显示请求详细信息
curl -v https://example.com
示例 11:静默模式(适合脚本)
response=$(curl -s https://api.example.com/status)
echo $response
| 参数 | 长参数 | 说明 |
|---|---|---|
-X METHOD |
--request METHOD |
指定 HTTP 方法 |
-H HEADER |
--header HEADER |
添加请求头 |
-d DATA |
--data DATA |
发送 POST 数据 |
-o FILE |
--output FILE |
输出到文件 |
-O |
--remote-name |
使用远程文件名保存 |
-I |
--head |
只显示响应头 |
-i |
--include |
输出中包含响应头 |
-v |
--verbose |
详细模式 |
-s |
--silent |
静默模式 |
-L |
--location |
跟随重定向 |
-u USER:PASS |
--user USER:PASS |
基本认证 |
-F FORM |
--form FORM |
multipart 表单数据 |
-b COOKIE |
--cookie COOKIE |
发送 Cookie |
-c FILE |
--cookie-jar FILE |
保存 Cookie |
-k |
--insecure |
跳过 HTTPS 证书验证 |
--cacert FILE |
指定 CA 证书 | |
--cert FILE |
客户端证书 | |
--key FILE |
客户端私钥 | |
-w FORMAT |
--write-out FORMAT |
输出自定义格式信息 |
-m SECONDS |
--max-time SECONDS |
最大执行时间 |
--retry N |
重试次数 | |
-A UA |
--user-agent UA |
设置 User-Agent |