How to post variables with curl in JSON
I am required to post variables to a website API using JSON format. After some research and using a test post server I came up with this string:
curl -H "Content-Type: application/json" -X POST -d '{"id":"value"}' http://posttestserver.com/post.php
Successfully dumped 0 post variables.
View it at http://www.posttestserver.com/data/2015/09/12/09.46.20574590076
Post body was 12 chars long.
However no variables are parsed from the string (it should find the variable "id" in this case). Instead everything is put into the post body.
The full post request can be seen at the given address:
Time: Sat, 12 Sep 15 09:46:20 -0700
Source ip: 178.112.221.72
Headers (Some may be inserted by server)
HTTP_CONNECTION = close
REQUEST_URI = /post.php
QUERY_STRING =
REQUEST_METHOD = POST
GATEWAY_INTERFACE = CGI/1.1
REMOTE_PORT = 53709
REMOTE_ADDR = 178.112.221.72
CONTENT_LENGTH = 12
CONTENT_TYPE = application/json
HTTP_ACCEPT = */*
HTTP_USER_AGENT = curl/7.43.0
HTTP_HOST = posttestserver.com
UNIQUE_ID = VfRW3NBx6hIAAHNyJToAAAAK
REQUEST_TIME_FLOAT = 1442076380.6991
REQUEST_TIME = 1442076380
No Post Params.
== Begin post body ==
'{id:value}'
== End post body ==
Upload contains PUT data:
'{id:value}'
Here the data appears both in "post body" and under PUT. But again no post parameters are listed.
Am I doing something wrong? Is it at all possible to post variables using JSON (the way you would by using id=value&id2=value2
with application/x-www-form-urlencoded
)?
PS I found a similar post (how to post with curl to REST/JSON service?), there it depends on the server. But in my case by using this test server I should see the actual "raw" request (quoting from posttestserver.com
"Thus, I've put together a simple service which will dump the contents of an* HTTP POST to a file which can be viewed at leisure."
).
You'll notice it did in fact show your data in the Post Body
section. When you send via CURL with application/json, it simply pumps that JSON into the body. If it were x-www-form-urlencoded
it would have serialized it into a format that PHP can natively understand eg: id=value
. Looks like it's working as intended, just the server doesnt' understand JSON.
If you want that particular service to understand your content properly, you'll need to serialize it to something of the standard x-www-form-urlencoded
format by doing simply -d "id=value"
上一篇: 角度弹簧发布json与数组
下一篇: 如何在JSON中使用curl发布变量