如何使用 curl 将 JSON 发布到 PHP

我可能大错特错了,但是我整个下午都在尝试在这个课间 PHP 框架教程中运行 Curl post 命令。我不明白的是 PHP 应该如何解释我的 POST,它总是以一个空数组的形式出现。

curl -i -X POST -d '{"screencast":{"subject":"tools"}}'  \
http://localhost:3570/index.php/trainingServer/screencast.json

(这里的斜杠只是为了不让我看起来像个白痴,但是我在 Windows 中使用 PHP 5.2执行了这个命令,在 Linux 服务器上也试过,与 Linux curl 版本相同)

我一定漏掉了什么,因为它看起来非常简单,帖子只是没有被正确解释,如果是的话,一切都会很好。

这就是我得到的回报:

HTTP/1.1 409 Conflict
Date: Fri, 01 May 2009 22:03:00 GMT
Server: Apache/2.2.8 (Win32) PHP/5.2.6
X-Powered-By: PHP/5.2.6
Transfer-Encoding: chunked
Content-Type: text/html; charset=iso-8859-1


{"screencast":{"id":null,"subject":null,"body":null,
"dataUrl":null,"dataMedium":null,"createdOn":null,"author":null}}
167809 次浏览

I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).

Try changing your curl request to:

curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}'  \
http://localhost:3570/index.php/trainingServer/screencast.json

and see if that helps any.

Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use

$data = file_get_contents("php://input");

to just retrieve the http body and handle it yourself. See PHP input/output streams.

From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.

You should escape the quotes like this:

curl -i -X POST -d '{\"screencast\":{\"subject\":\"tools\"}}'  \
http://localhost:3570/index.php/trainingServer/screencast.json

Normally the parameter -d is interpreted as form-encoded. You need the -H parameter:

curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json

You need to set a few extra flags so that curl sends the data as JSON.

command

$ curl -H "Content-Type: application/json" \
-X POST \
-d '{"JSON": "HERE"}' \
http://localhost:3000/api/url

flags

  • -H: custom header, next argument is expected to be header
  • -X: custom HTTP verb, next argument is expected to be verb
  • -d: sends the next argument as data in an HTTP POST request

resources