题
我可能离基地很远,但我整个下午都在努力跑步 卷曲后命令 在这个课间休息时 PHP 框架教程。我不明白的是 PHP 应该如何解释我的 POST,它总是以空数组的形式出现。
curl -i -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
(其中的斜杠只是为了让我看起来不像个白痴,但我使用 PHP 5.2 从 Windows 执行了这个,也在 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}}
解决方案
Jordans分析未填充$ _POST数组的原因是正确的。但是,您可以使用
$data = file_get_contents("php://input");
只需检索http正文并自行处理。请参阅 PHP输入/输出流。
从协议的角度来看,这实际上更正确,因为您还没有真正处理http多部分表单数据。另外,在发布请求时使用application / json作为内容类型。
其他提示
通常,参数 -d
被解释为表格编码。您需要 -H
参数:
curl -v -H "Content-Type: application/json" -X POST -d '{"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
我相信你得到一个空数组,因为PHP期望发布的数据采用Querystring格式(key = value& key1 = value1)。
尝试将您的卷曲请求更改为:
curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
并查看是否有帮助。
您需要设置一些额外的标志,以便curl 将数据作为JSON 发送。
命令
$ curl -H "Content-Type: application/json" \
-X POST \
-d '{"JSON": "HERE"}' \
http://localhost:3000/api/url
旗帜
-H
:自定义标头,下一个参数预计是标头-X
:自定义 HTTP 动词,下一个参数应为动词-d
:将下一个参数作为 HTTP POST 请求中的数据发送
资源
你应该逃避这样的引号:
curl -i -X POST -d '{\"screencast\":{\"subject\":\"tools\"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
不隶属于 StackOverflow