cURL 是一个强大的命令行工具,广泛用于与 URL 进行交互。它支持多种协议,包括 HTTP、HTTPS、FTP 等。本文将介绍一些常用的 cURL 命令及其用法,帮助您更好地利用这个工具。
1. 什么是 cURL?
cURL(Client URL)是一个开源的命令行工具和库,允许用户通过 URL 从命令行或脚本中发送和接收数据。它支持多种传输协议,使其在开发和自动化测试中非常实用。
2. cURL 基本用法
2.1 发送 GET 请求
发送 GET 请求是 cURL 的基本功能,使用以下命令:
curl http://example.com
2.2 发送 POST 请求
发送 POST 请求并携带数据:
curl -X POST -d "param1=value1¶m2=value2" http://example.com/api
或者以 JSON 格式发送数据:
curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://example.com/api
2.3 添加请求头
使用 -H
选项添加自定义请求头:
curl -H "Authorization: Bearer YOUR_TOKEN" http://example.com/api
2.4 下载文件
使用 -O
选项将文件下载到本地,文件名与服务器上的文件名相同:
curl -O http://example.com/file.zip
如果要自定义文件名,可以使用 -o
:
curl -o myfile.zip http://example.com/file.zip
2.5 上传文件
使用 -F
选项上传文件:
curl -F "file=@/path/to/file.txt" http://example.com/upload
2.6 处理 HTTPS 请求
对于 HTTPS 请求,您可能需要忽略 SSL 证书验证(仅用于测试环境):
curl -k https://example.com
2.7 显示请求和响应头
使用 -I
选项仅获取响应头:
curl -I http://example.com
如果要查看请求和响应的完整信息,可以使用 -v
(verbose)选项:
curl -v http://example.com
2.8 设置请求超时
使用 --max-time
设置请求的最大超时时间(单位为秒):
curl --max-time 10 http://example.com
3. 进阶用法
3.1 保存会话
使用 -c
选项保存 cookie 到文件中:
curl -c cookies.txt http://example.com
使用 -b
选项从文件中读取 cookie:
curl -b cookies.txt http://example.com
3.2 使用代理
通过代理服务器发送请求:
curl -x http://proxyserver:port http://example.com
3.3 进行性能测试
使用 -w
选项自定义输出格式,以获取性能数据:
curl -w "@curl-format.txt" -o /dev/null -s https://example.com
curl-format.txt
可以包含您希望输出的变量,如:
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n
4. 结论
cURL 是一款功能强大的命令行工具,适用于各种网络请求和数据传输场景。通过掌握这些常用命令,您可以更高效地进行 Web 开发和测试。