Curl 用法
cURL(Client URL)是一个功能强大的命令行工具,用于通过URL传输数据,支持多种协议(如HTTP/HTTPS、FTP、SFTP、SCP等)。它广泛用于API测试、文件传输、数据提交等场景。
安装
Linux (Debian/Ubuntu)
sudo apt-get install curl
macOS
brew install curl # 通过Homebrew安装/更新
Windows
- 从官网下载二进制文件
- 或使用Chocolatey:
choco install curl
基本用法
发起GET请求
curl https://example.com
保存响应到文件
curl -o custom_filename.html https://example.com # 自定义文件名
curl -O https://example.com/file.zip # 使用远程文件名
常用选项
选项 | 说明 |
---|---|
-v | 显示详细日志(请求头、响应头、SSL信息) |
-L | 自动跟随重定向 |
-s | 静默模式(隐藏进度条和错误信息) |
-i | 显示响应头 + 响应体 |
-I | 仅显示响应头(发送HEAD请求) |
-k | 跳过SSL证书验证(不安全,谨慎使用) |
-A | 设置User-Agent,如 -A "Mozilla/5.0" |
HTTP方法
POST请求(表单数据)
curl -X POST https://api.example.com/data -d "name=John&age=30"
POST请求(JSON数据)
curl -X POST -H "Content-Type: application/json" \
-d '{"name":"John", "age":30}' https://api.example.com/data
PUT/DELETE请求
curl -X PUT https://api.example.com/item/1 -d "data=example"
curl -X DELETE https://api.example.com/item/1
处理HTTP头
查看响应头
curl -I https://example.com
发送自定义头
curl -H "Authorization: Bearer token123" \
-H "X-Custom-Header: value" https://api.example.com
文件传输
上传文件(表单)
curl -F "file=@/path/to/file.txt" https://example.com/upload
上传文件(FTP)
curl -T file.txt ftp://example.com/upload/
断点续传
curl -C - -O https://example.com/large-file.zip
认证
基本认证(Basic Auth)
curl -u username:password https://example.com
Cookie管理
curl -c cookies.txt https://example.com/login # 保存Cookie
curl -b cookies.txt https://example.com/dashboard # 发送Cookie
高级功能
限速下载(100KB/s)
curl --limit-rate 100K -O https://example.com/large-file.zip
使用代理
curl -x http://proxy-server:8080 https://example.com
调试请求
curl --trace-ascii debug.txt https://example.com
实际示例
下载GitHub仓库
curl -L -O https://github.com/user/repo/archive/master.zip
模拟浏览器访问
curl -A "Mozilla/5.0" -H "Accept-Language: en-US" https://example.com
调试HTTPS请求
curl -v -k https://example.com # 查看SSL握手过程(忽略证书错误)
注意事项
- 敏感数据:避免在命令行中直接暴露密码,推荐使用
--netrc
或环境变量。 - HTTPS安全:生产环境中尽量不使用
-k
(跳过证书验证)。 - 命令顺序:组合选项时注意顺序(如
-L -O
需先重定向再保存文件)。 - 速率限制:使用
--limit-rate
避免占用过多带宽。