curl 是一个强大的命令行工具,用于在命令行或脚本中发起 HTTP 请求,与服务器通信。它可以用来下载网页、调试 API 接口、上传文件、发送表单等。几乎所有支持网络通信的协议 curl 都能处理,包括 HTTP、HTTPS、FTP、SFTP、SMTP 等。
# 一、curl 能做什么
| 功能 | 示例 |
|---|---|
| 获取网页内容 | curl https://example.com |
| 下载文件 | curl -O https://example.com/file.zip |
| 发送 POST 请求 | curl -X POST -d "name=Koen&age=20" https://example.com/api |
| 添加请求头 | curl -H "Authorization: Bearer TOKEN" https://api.example.com/data |
| 上传文件 | curl -F "file=@test.png" https://example.com/upload |
| 保存输出到文件 | curl https://example.com -o saved.html |
下面对常用功能做更详细的说明。
# 二、获取网页内容
curl <url>
会将 GET 请求返回结果直接输出在命令行。
保存输出到文件:
curl https://example.com -o index.html
index.html 会保存到当前命令行所在目录。
# 三、发送 POST 请求
一般用于测试接口是否正常:
curl -X POST -d "name=Koen&age=20" https://example.com/api
带上请求头和 JSON 请求体:
curl -X POST https://api.example.com/data \
-H "Authorization: Bearer abc123" \
-H "Content-Type: application/json" \
-d '{"key":"value"}'
另一个例子(登录接口):
curl -X POST -H "Content-Type: application/json" \
-d '{"username":"koen","password":"123456"}' \
https://example.com/api
# 四、上传文件
curl -F "file=@test.png" https://example.com/upload
-F 表示使用表单(multipart/form-data)的方式提交字段/文件。
| 部分 | 含义 |
|---|---|
file |
表单字段名,类似 <input type="file" name="file"> 的 name |
= |
分隔字段名与数据(文件) |
@test.png |
表示上传当前目录下名为 test.png 的文件 |
本质就是用 POST 请求上传文件的一种方式。
