第 2 课
Headers、方法与请求体
把 `-X`、`-H` 与 `-d` 选项映射到清晰的 HTTP 请求模型。
大多数 cURL 到代码的转换,都围绕三个概念:方法、headers 和请求体。
方法
-X 或 --request 设置 HTTP 方法:
curl -X PATCH https://api.example.com/users/42
没有 -X 时,cURL 通常发送 GET。带 -d 时,cURL 通常发送 POST。
Headers
-H 或 --header 添加 headers:
curl -H "Accept: application/json" -H "X-Request-Id: demo-1" https://api.example.com
按 HTTP 规则,header 名大小写不敏感,但应用代码中保留清晰名称更利于阅读。
请求体
-d、--data、--data-raw 和 --data-binary 会附加请求体内容:
curl -H "Content-Type: application/json" -d '{"name":"Ada"}' https://api.example.com/users
请求体本质上只是字节。Content-Type header 告诉服务器如何解释这些字节。
表单和 JSON 不一样
下面两个请求不等价:
curl -d "name=Ada&role=admin" https://api.example.com/users
curl -H "Content-Type: application/json" -d '{"name":"Ada","role":"admin"}' https://api.example.com/users
第一个是表单风格数据,第二个是 JSON。转换器可以翻译两者,但你的应用仍然需要服务器期待同一种内容类型。