使用 curl 发送 POST 请求
非常实用的问题 👍
curl 发送 POST 请求是日常调接口最常用的命令之一。
我们来从最常见到稍进阶的用法系统讲一遍 👇
✅ 一、最基本语法
curl -X POST <URL> -d "<数据>"
或者简写:
curl -d "<数据>" <URL>
-X POST 指明请求方法是 POST
-d 指定要发送的数据(默认 Content-Type 为 application/x-www-form-urlencoded)
🔹 示例:
curl -X POST https://api.example.com/login -d "username=allen&password=123456"
服务器收到的内容相当于传统表单提交:
Content-Type: application/x-www-form-urlencoded
Body: username=allen&password=123456
✅ 二、发送 JSON 数据(最常用)
如果接口要求 Content-Type: application/json,你必须手动加上 -H 头。
curl -X POST https://api.example.com/login \
-H "Content-Type: application/json" \
-d '{"username": "allen", "password": "123456"}'
📘 说明:
-H添加请求头(Header)-d后面跟 JSON 字符串(注意双引号内的 JSON 要符合语法)
✅ 三、发送文件内容
假设你有一个 JSON 文件 data.json,内容如下:
{
"username": "allen",
"password": "123456"
}
可以这样发:
curl -X POST https://api.example.com/login \
-H "Content-Type: application/json" \
-d @data.json
👉 @data.json 表示读取文件内容作为请求体。
✅ 四、带认证或自定义头部
如果接口需要 token 或其他 header:
curl -X POST https://api.example.com/upload \
-H "Authorization: Bearer <你的token>" \
-H "Content-Type: application/json" \
-d '{"file": "test.png"}'
✅ 五、带文件上传(multipart/form-data)
例如表单上传文件(最常见于图像或附件接口):
curl -X POST https://api.example.com/upload \
-F "file=@/path/to/photo.png" \
-F "user=allen"
注意:
-F会自动设置Content-Type: multipart/form-data
✅ 六、显示响应头和状态码
curl -v -X POST ...
或:
curl -i -X POST ...
-v:verbose 模式(详细打印请求过程)-i:显示响应头 + body
如果只想看状态码:
curl -o /dev/null -s -w "%{http_code}\n" -X POST ...
✅ 七、综合示例(最实用)
curl -X POST https://api.example.com/api/v1/user/create \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 123456789" \
-d '{"name": "Allen Zhu", "email": "allen@example.com"}' \
-i
输出示例:
HTTP/1.1 200 OK
Content-Type: application/json
{"code":0,"msg":"success","data":{"id":1234}}
✅ 八、额外技巧
| 功能 | 参数 | 说明 |
|---|---|---|
| 设置超时 | --max-time 5 |
最多等待 5 秒 |
| 保存响应 | -o result.json |
把响应保存到文件 |
| 禁止输出进度条 | -s |
静默模式 |
| 指定请求头 | -H "HeaderName: value" |
添加任意 header |
🧠 总结一句话
| 场景 | 命令 |
|---|---|
| 表单 POST | curl -d "a=1&b=2" URL |
| JSON POST | curl -H "Content-Type: application/json" -d '{"a":1}' URL |
| 文件 POST | curl -F "file=@a.png" URL |
是否要我帮你总结一份「最常用 curl POST 命令速查表」?(涵盖 json、表单、文件上传、header、token、代理 等常用场景)

浙公网安备 33010602011771号