curl命令:从基础到高级用法详解
安装与验证
curl预装在大多数Linux发行版和macOS中。Windows用户可从官网下载二进制包。验证安装:
curl --version
输出应显示版本信息及支持的协议列表(如HTTP/HTTPS/FTP)。
基础请求语法
基本命令结构:
curl [选项] [URL]
- GET请求(默认):
curl https://api.example.com/data
- 显示详细过程(
-v
):curl -v https://example.com # 显示请求头/响应头
核心功能详解
1. 数据控制
选项 | 作用 | 示例 |
---|---|---|
-o FILE |
保存到文件 | curl -o page.html https://example.com |
-O |
使用远程文件名保存 | curl -O https://example.com/image.png |
-d DATA |
POST表单数据 | curl -d "name=Alice&age=30" https://api.example.com/users |
-F |
文件上传 | curl -F "file=@photo.jpg" https://upload.example.com |
2. 头部操作
# 自定义请求头
curl -H "Content-Type: application/json" https://api.example.com
# 查看响应头
curl -I https://example.com # 仅显示头部
3. 认证机制
# 基础认证
curl -u username:password https://secure.example.com
# Bearer Token
curl -H "Authorization: Bearer TOKEN" https://api.example.com
4. 网络调试
curl --limit-rate 100K https://largefile.example.com # 限速100KB/s
curl --retry 5 https://unstable.example.com # 失败重试5次
curl --proxy http://proxy.example.com:8080 https://target.com
进阶应用场景
JSON API交互
# POST JSON数据
curl -H "Content-Type: application/json" \
-d '{"title":"Hello","content":"World"}' \
https://api.example.com/posts
文件分块下载
curl -r 0-999 https://example.com/large.zip -o part1.zip # 下载0-999字节
curl -r 1000-1999 https://example.com/large.zip -o part2.zip
Cookie会话保持
# 保存Cookie到文件
curl -c cookies.txt https://login.example.com
# 使用Cookie访问
curl -b cookies.txt https://dashboard.example.com
错误处理指南
常见错误码及解决方案:
错误码 | 含义 | 解决方法 |
---|---|---|
6 | 无法解析主机 | 检查DNS或使用--resolve 参数 |
7 | 连接失败 | 检查网络/防火墙设置 |
22 | HTTP 4xx/5xx响应 | 检查URL/权限/请求参数 |
60 | SSL证书错误 | 添加-k 跳过验证(不推荐) |
调试建议:
curl -v --trace-ascii debug.log https://problematic-site.com
安全最佳实践
-
敏感数据处理:
# 使用环境变量避免密码泄露 export API_KEY="secret" curl -H "Authorization: $API_KEY" https://api.example.com
-
证书验证:
- 始终使用
https
- 避免
-k
(除非测试环境) - 自定义CA证书:
curl --cacert /path/to/ca.pem https://site.com
- 始终使用
-
输入过滤:
# 使用引号防止注入攻击 curl "https://api.example.com/search?q=$(echo $QUERY | sed 's/[^a-z]//g')"
性能优化技巧
- 启用HTTP/2:
curl --http2 https://example.com
- 连接复用:
curl -v --next https://example.com/page2 \ --next https://example.com/page3
- 压缩传输:
curl --compressed https://large-content.example.com
替代方案对比
工具 | 优势 | 劣势 |
---|---|---|
curl | 协议支持全面/脚本集成强 | 命令行交互不够直观 |
wget | 递归下载/断点续传优秀 | 功能较单一 |
HTTPie | 人性化输出/易读语法 | 依赖Python环境 |
实战案例:监控网站状态
创建监控脚本check_site.sh
:
#!/bin/bash
RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" https://example.com)
if [ "$RESPONSE" -ne 200 ]; then
echo "ALERT: Site down! Code $RESPONSE" | mail -s "Site Failure" admin@example.com
fi
通过cron定时运行:
* * * * * /path/to/check_site.sh # 每分钟检查
扩展学习资源
- 官方文档:
man curl
或 curl.se/docs/ - 交互式教程:https://reqbin.com/curl
- 在线沙盒:https://www.online-ide.com/online_curl_editor
正文到此结束
相关文章
热门推荐
评论插件初始化中...