Curl 是一款强大的命令行工具,用于发送 HTTP/HTTPS 等网络请求,支持下载、上传、认证、调试等场景。以下是核心用法整理,结合场景化示例和实用技巧:

# 语法格式
curl [参数] [URL] 命令 | 说明 |
|---|---|
curl --help | 查看常用选项(简洁版) |
curl --help all | 查看所有选项(详细版,适合进阶) |
# 输出:Curl 版本、支持的协议(HTTP/HTTPS/FTP 等)
curl --version
# 获取网页内容
curl https://example.com
# 下载文件,保留原文件名(file.zip)
curl -O https://a.com/file.zip
# 下载文件,自定义文件名(myfile.zip)
curl -o myfile.zip https://a.com/file.zip
# 跟随重定向(301/302)
curl -L https://a.com/redirect
# 等价于浏览器提交表单,Content-Type 默认为 application/x-www-form-urlencoded
curl -d "name=Jack&age=20" https://api.example.com/user
# json请求
curl -H "Content-Type: application/json" \
-d '{"name": "Jack", "age": 20}' \
https://api.example.com/user
# -F 模拟表单上传文件,@指定本地文件路径
curl -F "avatar=@/path/to/avatar.jpg" \
-F "username=Jack" \
https://api.example.com/upload
# 自动在请求头添加 Authorization: Basic base64编码(用户名:密码)
curl -u username:password https://api.example.com/admin
# 用于 OAuth2 等 Token 认证场景
curl -H "Authorization: Bearer YOUR_TOKEN" https://api.example.com/data
# 模拟客户端(如 App、爬虫)或添加业务头信息
curl -H "User-Agent: MyApp/1.0" \
-H "X-Custom-Header: value" \
https://example.com
# 输出:请求头、响应头、SSL 握手细节、状态码等完整过程
curl -v https://example.com
# 场景:检查缓存(Cache-Control)、状态码(200/404)、重定向(301)
curl -I https://example.com
# 忽略 SSL 证书错误(如自签名证书
curl -k https://localhost:8443
# 双向认证场景,携带客户端证书访问服务
curl --cert mycert.pem https://example.com
# 不显示进度/错误,适合脚本自动化
curl -s https://example.com > output.txt
# 续传中断的下载(-C - 自动识别断点位置)
curl -C - -O https://a.com/large.zip
# 限制速度为 1MB/s,避免占满带宽
curl --limit-rate 1M -O https://a.com/large.iso
# 场景:公司内网代理(需配合代理工具)
curl -x http://proxy:8080 https://example.com
# 同时显示响应头和内容(-I 仅显示头,-i 显示头+内容)
curl -i https://example.com 总结:Curl 的核心优势
-v 详细输出 +-i 头信息,快速定位网络问题。遇到复杂场景时,可组合参数(如 curl -v -L -o output.txt https://example.com 同时实现跟随重定向、调试、下载),灵活应对需求!
#Curl #网络请求 #http