如何通过 JSON 文件为 curl 传递有效负载? [英] How to pass payload via JSON file for curl?

查看:24
本文介绍了如何通过 JSON 文件为 curl 传递有效负载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过 curl 执行以下命令成功创建一个地方:

I can successfully create a place via curl executing the following command:

$ curl -vX POST https://server/api/v1/places.json -d "
  auth_token=B8dsbz4HExMskqUa6Qhn& 
  place[name]=Fuelstation Central& 
  place[city]=Grossbeeren& 
  place[address]=Buschweg 1& 
  place[latitude]=52.3601& 
  place[longitude]=13.3332& 
  place[washing]=true& 
  place[founded_at_year]=2000& 
  place[products][]=diesel& 
  place[products][]=benzin 
"

服务器返回HTTP/1.1 201 Created.
现在我想将有效负载存储在如下所示的 JSON 文件中:

The server returns HTTP/1.1 201 Created.
Now I want to store the payload in a JSON file which looks like this:

// testplace.json
{
  "auth_token" : "B8dsbz4HExMskqUa6Qhn",
  "name" : "Fuelstation Central",
  "city" : "Grossbeeren",
  "address" : "Buschweg 1",
  "latitude" : 52.3601,
  "longitude" : 13.3332,
  "washing" : true,
  "founded_at_year" : 2000,
  "products" : ["diesel","benzin"]
}

所以我修改命令执行如下:

So I modify the command to be executed like this:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json

返回HTTP/1.1 401 Unauthorized 失败.为什么?

推荐答案

curl 发送带有默认内容类型 application/x-www-form-urlencoded 的 POST 请求.如果要发送 JSON 请求,则必须指定正确的内容类型标头:

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json 
--header "Content-Type: application/json"

但这只有在服务器接受 json 输入时才有效.url末尾的.json可能只表示output是json,并不一定意味着它也会处理json inputem>.API 文档应该给你一个关于它是否存在的提示.

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

您收到 401 而不是其他错误的原因可能是因为服务器无法从您的请求中提取 auth_token.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

这篇关于如何通过 JSON 文件为 curl 传递有效负载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆