【问题标题】:How to post JSON to PHP with curl如何使用 curl 将 JSON 发布到 PHP
【发布时间】:2010-10-23 05:53:12
【问题描述】:

我可能有点离题,但我整个下午都在尝试在这个课间 PHP 框架教程中运行 the curl post command。我不明白的是 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 冲突 日期:格林威治标准时间 2009 年 5 月 1 日星期五 22:03:00 服务器:Apache/2.2.8 (Win32) PHP/5.2.6 X-Powered-By: PHP/5.2.6 传输编码:分块 内容类型:文本/html;字符集=iso-8859-1 {"screencast":{"id":null,"subject":null,"body":null, "dataUrl":null,"dataMedium":null,"createdOn":null,"author":null}}

【问题讨论】:

  • 能否请您也复制粘贴您的 .php 文件?您确定 URL localhost:3570/index.php/trainingServer/screencast.json 运行您的脚本吗?它看起来不像 PHP URL。
  • @pts; Peter 正在使用某种 MVC 框架,请查看该 URL 中的 index.php。
  • @pts 我将 Delphi 用于 PHP(因此是 :3570)和没有 .htaccess 文件的 Recess MVC 框架,因此是 url 中的 index.php/。
  • 别忘了发送application/json
  • 在简单的双引号内嵌入双引号时,不需要转义。

标签: php rest post


【解决方案1】:

通常参数-d 被解释为格式编码。您需要-H 参数:

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

【讨论】:

    【解决方案2】:

    Jordans 对为什么没有填充 $_POST 数组的分析是正确的。但是,您可以使用

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

    只是检索 http 正文并自己处理。见PHP input/output streams

    从协议的角度来看,这实际上更正确,因为无论如何您并没有真正处理 http 多部分表单数据。此外,在发布请求时使用 application/json 作为内容类型。

    【讨论】:

    • 做 json_decode(file_get_contents("php://input"), true) 工作。谢谢
    • 真的对我的情况也有帮助!谢谢埃米尔 H!
    • 太棒了。我在 Zend 认为它正在剥离帖子时遇到了很多麻烦。一个简单的提取对我有用。 Peter Turners 还添加了 json_decode() 提供了一个 \stdClass 对象。我将它用于 Garmin API ping 响应
    【解决方案3】:

    我相信您得到的是一个空数组,因为 PHP 期望发布的数据采用查询字符串格式 (key=value&key1=value1)。

    尝试将您的 curl 请求更改为:

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

    看看有没有帮助。

    【讨论】:

    • 是的,-H "Content-Type: application/json" 对我不起作用。
    【解决方案4】:

    您需要设置一些额外的标志,以便 curl 以 JSON 格式发送数据。

    命令

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

    标志

    • -H: 自定义标题,下一个参数应该是标题
    • -X: 自定义 HTTP 动词,下一个参数应该是动词
    • -d:将下一个参数作为 HTTP POST 请求中的数据发送

    资源

    【讨论】:

      【解决方案5】:

      你应该像这样转义引号:

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

      【讨论】:

      • 在 Windows 上这实际上对我有用,但使用双引号将整个 json 字符串括起来。
      • 在 Windows 上,您必须按照 Josef 上面的建议转义双引号。他是对的。
      猜你喜欢
      • 1970-01-01
      • 2011-12-19
      • 2020-12-09
      • 2012-06-20
      相关资源
      最近更新 更多