CURL(Client URL)是一个强大的命令行工具,用于通过各种网络协议与服务器进行数据传输。它支持 HTTP、HTTPS、FTP、SFTP 等多种协议,广泛应用于 API 测试、数据获取、文件传输等场景。以下是 CURL 命令的详细用法:
- 选项:控制 CURL 的行为(如请求方法、头部信息、认证等)。
- URL:目标服务器的地址(需包含协议,如
http://example.com)。
# 最简单的GET请求 curl https://example.com # 获取详细响应信息(包括头部) curl -v https://example.com # 仅获取响应头部 curl -I https://example.com # 保存响应内容到文件 curl -o response.html https://example.com
# 提交表单数据(表单格式) curl -X POST https://example.com/api/submit --data "name=John&age=30" # 提交JSON数据(需指定Content-Type) curl -X POST https://example.com/api/data -H "Content-Type: application/json" -d '{"key": "value", "array": [1, 2, 3]}' # 从文件读取数据并提交 curl -X POST https://example.com/upload -T data.json
# 添加自定义请求头 curl -H "User-Agent: MyApp/1.0" https://example.com # 基本认证(用户名:密码) curl -u username:password https://example.com/auth # Bearer Token认证 curl -H "Authorization: Bearer YOUR_TOKEN" https://example.com/api # 发送Cookie curl -b "session_id=12345" https://example.com
# 使用代理服务器 curl -x proxy.example.com:8080 https://example.com # 设置超时时间(秒) curl -m 10 https://example.com # 限制带宽(KB/s) curl --limit-rate 100 https://example.com/large-file
# 下载文件并显示进度 curl -# -O https://example.com/file.zip # 断点续传(已下载文件可继续下载) curl -C - -O https://example.com/file.zip # 上传文件到服务器(PUT方法) curl -X PUT https://example.com/upload -T local-file.txt
# 忽略HTTPS证书验证(不安全,仅测试用) curl -k https://example.com # 指定客户端证书 curl --cert client.crt --key client.key https://example.com # 信任CA证书文件 curl --cacert ca.crt https://example.com
# 模拟Chrome浏览器请求 curl -H "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" https://example.com # 跟踪重定向(默认跟随3次) curl -L https://example.com/redirect
# 测试DELETE API curl -X DELETE https://example.com/api/item/123 -H "Authorization: Bearer TOKEN" # 查看请求与响应的详细日志 curl -v https://example.com/api/endpoint
# 从文本文件读取URL列表并批量请求 cat urls.txt | while read url; do curl -s $url | head -n 10; done # 在Shell脚本中使用CURL #!/bin/bash URL="https://api.example.com/data" TOKEN="your_token_here" response=$(curl -s -H "Authorization: Bearer $TOKEN" $URL) echo "Response: $response"
| 选项 |
描述 |
-v / --verbose |
显示详细的通信过程(调试用) |
-X / --request |
指定请求方法(GET/POST/PUT/DELETE 等) |
-d / --data |
发送 POST 数据(表单格式) |
-H / --header |
添加自定义请求头 |
-u / --user |
基本认证(用户名:密码) |
-o / --output |
保存响应到文件 |
-O / --remote-name |
按远程文件名保存响应 |
-k / --insecure |
忽略 HTTPS 证书验证 |
-x / --proxy |
使用代理服务器 |
-m / --max-time |
设置最大请求时间(秒) |
- URL 编码:如果参数包含特殊字符(如空格、
&、=),需用%20等编码替换,或用单引号包裹参数(如'name=John Doe')。
- 安全性:避免在命令中明文写入密码,可通过环境变量(如
CURL_USER_PASSWORD)或配置文件传递认证信息。
- Windows 系统:部分选项语法需调整(如双引号替代单引号),建议使用 PowerShell 或 Git Bash 运行 CURL。
通过灵活组合上述选项,CURL 可以满足几乎所有网络请求场景。如需更详细的帮助,可运行
curl --help或查看
官方文档。