在 cURL 中,-d 和 --data 实际上是完全相同的参数,只是长短形式的不同。但 cURL 提供了多种数据发送方式,适用于不同的场景。
-d 和 --data 的区别
bash# 两者完全等价 curl -d "name=value" https://api.example.com curl --data "name=value" https://api.example.com
数据发送方式对比
| 参数 | 用途 | Content-Type | 示例 |
|---|---|---|---|
-d / --data | 发送数据(默认 URL 编码) | application/x-www-form-urlencoded | -d "name=value" |
--data-ascii | 发送 ASCII 文本 | application/x-www-form-urlencoded | --data-ascii "text" |
--data-binary | 发送二进制数据 | 不设置 | --data-binary @file.bin |
--data-urlencode | URL 编码数据 | application/x-www-form-urlencoded | --data-urlencode "name=value" |
--data-raw | 原样发送(不处理 @) | application/x-www-form-urlencoded | --data-raw "@username" |
详细用法示例
bash# 1. 基本数据发送(URL 编码) curl -X POST https://api.example.com/login \ -d "username=admin&password=123456" # 2. 发送 JSON 数据(需要手动设置 Content-Type) curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d '{"name":"张三","age":25}' # 3. 从文件读取数据 curl -X POST https://api.example.com/upload \ -d @data.json # 4. 发送二进制文件 curl -X POST https://api.example.com/upload \ -H "Content-Type: application/octet-stream" \ --data-binary @/path/to/file.bin # 5. URL 编码特殊字符 curl -X POST https://api.example.com/search \ --data-urlencode "query=hello world!" # 结果:query=hello%20world%21 # 6. 原样发送(不处理 @ 符号) curl -X POST https://api.example.com/webhook \ --data-raw "@channel message here"
多数据段发送
bash# 发送多个数据段 curl -X POST https://api.example.com/form \ -d "name=张三" \ -d "email=zhangsan@example.com" \ -d "age=25" # 混合使用 curl -X POST https://api.example.com/mixed \ -d "title=测试" \ --data-urlencode "content=Hello World!" \ --data-binary @attachment.pdf
不同数据格式示例
bash# 表单数据(application/x-www-form-urlencoded) curl -X POST https://api.example.com/form \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "field1=value1&field2=value2" # JSON 数据(application/json) curl -X POST https://api.example.com/api \ -H "Content-Type: application/json" \ -d '{"key":"value","array":[1,2,3]}' # XML 数据(application/xml) curl -X POST https://api.example.com/soap \ -H "Content-Type: application/xml" \ -d '<?xml version="1.0"?><root><item>value</item></root>' # 纯文本(text/plain) curl -X POST https://api.example.com/log \ -H "Content-Type: text/plain" \ --data-binary @log.txt
注意事项
- 默认行为:
-d会自动设置Content-Type: application/x-www-form-urlencoded - 覆盖 Content-Type:如果需要发送 JSON,必须手动设置
-H "Content-Type: application/json" - 文件读取:
-d @filename会从文件读取内容 - @ 符号处理:
--data-raw可以防止@被解释为文件路径 - URL 编码:
--data-urlencode会自动对特殊字符进行编码
实战技巧
bash# 发送复杂 JSON(使用 heredoc) curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d @- <<'EOF' { "user": { "name": "张三", "email": "zhangsan@example.com", "roles": ["admin", "user"] }, "settings": { "theme": "dark", "notifications": true } } EOF # 发送 Base64 编码的数据 curl -X POST https://api.example.com/upload \ -H "Content-Type: application/json" \ -d "{\"file\":\"$(base64 -w 0 image.png)\"}"