基础用法
发送GET请求
curl https://example.com
- 作用:获取网页内容
- 常用参数:
-o 文件名
:保存到文件(如curl -o page.html https://example.com
)-L
:自动跟随重定向(解决301/302跳转)
发送POST请求
curl -X POST -d 'name=John&age=30' https://api.example.com/user
- 参数说明:
-X POST
:指定POST方法(默认GET)-d
:发送表单数据(自动设置Content-Type: application/x-www-form-urlencoded
)
- 发送JSON数据:
curl -X POST -H "Content-Type: application/json" -d '{"name":"John"}' https://api.example.com
-H
添加请求头
高级功能
文件上传
curl -F "file=@/path/to/photo.jpg" https://upload.example.com
-F
:模拟表单文件上传(自动生成multipart/form-data
)
认证与Cookie
- Basic认证:
curl -u username:password https://auth.example.com
- 使用Cookie:
curl -b "session=abc123" https://example.com # 发送Cookie curl -c cookies.txt https://example.com # 保存Cookie到文件
设置代理
curl -x http://proxy-server:8080 https://example.com
调试与查看详情
curl -v https://example.com # 显示请求/响应头(-vv更详细) curl -I https://example.com # 仅显示响应头(HEAD请求)
实用场景示例
下载文件
curl -O https://example.com/file.zip # 保存原名文件 curl -o custom_name.zip https://example.com/file.zip
限速下载(避免占用带宽)
curl --limit-rate 200K -O https://example.com/largefile.iso
断点续传
curl -C - -O https://example.com/bigfile.tgz
测试API响应
curl -X POST -H "Authorization: Bearer token123" -d '{"query":"test"}' https://api.example.com/data
安全注意事项
- 敏感信息隐藏:
- 避免在命令中直接写密码,使用
-u username:
交互输入密码。
- 避免在命令中直接写密码,使用
- HTTPS验证:
- 默认验证证书,跳过验证用
-k
(不推荐生产环境使用)。
- 默认验证证书,跳过验证用
- 防命令注入:
用户输入需严格过滤,避免拼接命令。
常见问题解决
- 中文乱码:添加
-H 'Accept-Language: en-US'
或转换编码(如iconv
)。 - 连接超时:用
--connect-timeout 10
设置超时秒数。 - 慢速网络:用
--retry 3
自动重试失败请求。
cURL 的核心价值在于其灵活性与脚本化能力,通过组合参数(如 -H
、-d
、-o
),可自动化完成数据采集、API测试、文件传输等任务,建议:
- 掌握常用参数(
-v
、-L
、-O
)。 - 复杂操作先测试再嵌入脚本。
- 查阅手册:
curl --help
或 官方文档。
引用说明参考 cURL官方文档、Mozilla开发者网络(MDN),并结合实践经验编写,安全建议遵循OWASP最佳实践。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/6502.html