cURL 常用操作指南

cURL (Client URL) 是一个强大的命令行工具,用于传输数据,支持多种协议(HTTP/HTTPS/FTP/SFTP等)。它广泛用于 API 测试、文件传输和网络调试。


1. 基本请求

GET 请求

curl https://example.com

POST 请求

curl -X POST https://example.com/api \
     -d "key1=value1&key2=value2"

2. 请求头设置

添加自定义 Header

curl -H "Authorization: Bearer token123" \
     -H "User-Agent: MyApp/1.0" \
     https://example.com/api

3. 文件上传 & 下载

上传文件

curl -X POST https://example.com/upload \
     -F "file=@/path/to/file.txt" \
     -F "name=myfile"

下载文件

curl -O https://example.com/file.zip  # 保存为原文件名
curl -o custom_name.zip https://example.com/file.zip  # 自定义文件名

4. 认证 & Cookies

Basic Auth

curl -u username:password https://example.com

5. 调试 & 高级选项

显示详细请求信息

curl -v https://example.com  # 显示请求 & 响应 Headers
curl --trace-ascii debug.txt https://example.com  # 输出调试信息到文件

跟随重定向

curl -L https://example.com  # 自动跳转

限速下载

curl --limit-rate 100K -O https://example.com/largefile.zip

6. 代理设置

HTTP/HTTPS 代理

curl -x http://proxy-server:8080 https://example.com

SOCKS5 代理

curl --socks5 127.0.0.1:1080 https://example.com

7. 保存响应到变量(Bash)

response=$(curl -s https://example.com/api)
echo "$response"

8. 常用组合命令

检查 API 返回状态码

curl -s -o /dev/null -w "%{http_code}" https://example.com/api

测试 API 响应时间

curl -w "DNS: %{time_namelookup} | Connect: %{time_connect} | Total: %{time_total}\n" \
     -o /dev/null -s https://example.com

总结

用途 命令示例
GET 请求 curl https://example.com
POST 请求 curl -X POST -d "data" https://example.com/api
JSON 请求 curl -H "Content-Type: application/json" -d '{"key":"value"}'
下载文件 curl -O https://example.com/file.zip
上传文件 curl -F "file=@localfile.txt" https://example.com/upload
认证 curl -u user:pass https://example.com
代理 curl -x http://proxy:8080 https://example.com
调试 curl -v https://example.com

cURL 功能非常强大,适用于自动化脚本、API 测试和网络调试。更多选项可查看 man curlcurl --help


Revision #1
Created 26 May 2025 01:17:25 by Admin
Updated 26 May 2025 01:19:04 by Admin