【发布时间】:2011-06-22 19:03:39
【问题描述】:
我正在实现一个 PHP 脚本,它接收一个 HTTP POST 消息,正文中包含一个 json 字符串,与“报告”参数相关联。所以 HTTP POST 报告=。 我正在使用 SimpleTest(PHP 单元测试)对此进行测试。
我构建了 json:
$array = array("type" => "start"); // DEBUG
$report = json_encode($array);
我发送 POST:
$this->post(LOCAL_URL, array("report"=>$json));
(从 SimpleTest 调用 WebTestCase 类中的方法)。
SimpleTest 说它发送这个:
POST /Receiver/web/report.php HTTP/1.0
Host: localhost:8888
Connection: close
Content-Length: 37
Content-Type: application/x-www-form-urlencoded
report=%7B%22type%22%3A%22start%22%7D
我收到这样的:
$report = $_POST['report'];
$logger->debug("Content of the report parameter: $report");
$json = json_decode($report);
上面的调试语句给了我:
Content of the report parameter: {\"type\":\"start\"}
当我解码时,它给出了错误
Syntax error, malformed JSON
“application/x-www-form-urlencoded”内容类型由 SimpleTest 自动选择。当我将其设置为“应用程序/json”时,我的 PHP 脚本看不到任何参数,因此找不到“报告”变量。 我想 url 编码出了点问题,但我在这里迷失了如何让 json 交叉。
另外,这里通常的做法是什么?即使您只发送整个 json 正文,是否也使用键/值方法?或者我可以将 json 字符串转储到 HTTP POST 的正文中并以某种方式读出吗? (在没有变量指向的情况下,我没有成功地实际读出它)。
无论如何,我希望这个问题能得到一些明确的说明。 提前致谢。
节食
【问题讨论】:
-
问题确实是魔术引号,显然它在我的 MAMP 版本中默认启用。如果我现在将它作为键/值对发送(json 是值),并且没有定义内容类型,它就像一个魅力。但是不能使用内容类型 application/json ,但我想这样做的原因是我违反了一些 RFC 类型的东西,我明确不想这样做。非常感谢 @johncartwright 和 @hakre 的出色帮助!
-
提示:选择一个答案作为“答案”,例如约翰的。
-
@hakre :完成,感谢您的提示 :)
标签: php json http urlencode simpletest