基础用法
-
获取网页内容
curl https://www.example.com
输出目标URL的HTML源码
-
保存文件
curl -O https://example.com/image.jpg # 保存为原始文件名 curl -o custom_name.jpg https://example.com/image.jpg # 自定义文件名
-
发送GET请求
curl "https://api.example.com/data?key=value"
高级功能
HTTP请求方法
curl -X POST https://api.example.com/login # POST请求 curl -X PUT https://api.example.com/update # PUT请求 curl -X DELETE https://api.example.com/item/1 # DELETE请求
提交表单数据
curl -d "username=admin&password=123456" https://example.com/login # 表单数据 curl -d "@data.json" -H "Content-Type: application/json" https://api.example.com # JSON数据
设置请求头
curl -H "Authorization: Bearer token123" https://api.example.com curl -H "User-Agent: MyApp/1.0" -H "Accept-Language: en-US" https://example.com
处理Cookie
curl -c cookies.txt https://example.com/login # 保存Cookie curl -b cookies.txt https://example.com/dashboard # 使用Cookie
调试与诊断
curl -v https://example.com # 显示详细通信过程 curl -I https://example.com # 仅显示响应头
实用场景示例
下载文件并断点续传
curl -C - -O https://example.com/large_file.zip
通过代理访问
curl -x http://proxy-server:8080 https://example.com
FTP文件上传
curl -T localfile.txt ftp://ftp.example.com --user user:password
限速下载(100KB/s)
curl --limit-rate 100K -O https://example.com/file.iso
安全注意事项
-
HTTPS证书验证
cURL默认验证SSL证书,若遇自签名证书,可临时跳过验证(不推荐):curl -k https://untrusted-site.com
-
敏感信息保护
避免在命令中直接暴露密码:curl -u username:password https://example.com # 密码会出现在历史记录
改用交互式输入:
curl -u username https://example.com # 提示输入密码
常见问题解决
-
中文乱码:
使用iconv
转码:curl https://example.com | iconv -f gbk -t utf-8
-
连接超时:
设置超时时间:curl --connect-timeout 10 https://example.com
-
跟随重定向:
添加-L
参数:curl -L https://example.com
cURL是开发者必备的”瑞士军刀”,通过组合不同参数可应对90%的网络数据传输需求,关键参数速查:
-O
:保存文件-d
:提交数据-H
:设置请求头-v
:调试模式-L
:跟随重定向
引用说明参考cURL官方文档(https://curl.se/docs/)及Mozilla开发者网络(MDN)HTTP协议标准,实践示例基于Linux/macOS终端环境测试,安全建议遵循OWASP命令行安全指南。
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/6176.html