curl是一个强大的命令行工具,用于通过URL语法传输数据,支持多种协议,包括HTTP、HTTPS、FTP、SFTP、SCP等。它是调试API、下载文件、测试网站等场景下的重要工具。
curl [选项] [URL...]
| 选项 | 描述 |
|---|---|
-X, --request |
指定HTTP请求方法(GET、POST、PUT等) |
-H, --header |
设置HTTP请求头 |
-d, --data |
发送POST请求的数据 |
-F, --form |
发送multipart/form-data数据 |
-o, --output |
将输出保存到文件 |
-O, --remote-name |
使用远程文件名保存输出 |
-I, --head |
只显示响应头信息 |
-L, --location |
跟随重定向 |
-u, --user |
设置用户名和密码 |
-k, --insecure |
允许不安全的SSL连接 |
-v, --verbose |
显示详细的连接信息 |
-s, --silent |
静默模式(不显示进度信息) |
获取网页内容:
curl https://api.example.com/users
发送JSON数据:
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"张三","email":"zhangsan@example.com"}' \
https://api.example.com/users
只获取响应头信息:
curl -I https://www.example.com
下载文件并保存:
# 保存为指定文件名
curl -o data.zip https://example.com/file.zip
# 使用远程文件名保存
curl -O https://example.com/file.zip
使用基本认证:
curl -u username:password https://api.example.com/data
# 或只输入用户名,密码在提示中输入
curl -u username https://api.example.com/data
上传文件:
# 上传单个文件
curl -F "file=@/path/to/local/file" https://example.com/upload
# 上传多个文件
curl -F "file1=@/path/to/file1" -F "file2=@/path/to/file2" https://example.com/upload
显示详细请求信息:
curl -v https://api.example.com/endpoint
# 更详细的信息(包含请求和响应的头和数据)
curl --trace-ascii debug.txt https://api.example.com/endpoint
# 1. 限制传输速度(每秒10KB)
curl --limit-rate 10K -O https://example.com/largefile.zip
# 2. 断点续传
curl -C - -O https://example.com/largefile.zip
# 3. 设置超时时间
curl --connect-timeout 10 --max-time 30 https://example.com
# 4. 设置User-Agent
curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" https://example.com
# 5. 使用代理
curl -x http://proxy.example.com:8080 https://example.com
# 6. 保存和发送Cookie
curl -c cookies.txt -b cookies.txt https://example.com
# 7. 压缩传输
curl --compressed https://example.com
# 8. 测试网站响应时间
curl -w "%{time_total}\n" -o /dev/null -s https://example.com
-X指定其他方法-d发送数据时,curl会自动将请求方法改为POST-k选项