我有一个托管在子域上的 PHP API。
如果我从 PHP 提交 POST 请求,接收 API 会读取 JSON 参数。 当我从命令行提交时,它没有。
我对 API 端点的 PHP Curl 调用是这样的:
<?php
$url = "https://MySubdomain/MyAPIEndpoint.php";
$headerfields = array(
'Accept:application/json',
'Content-Type: application/json',
);
$postfields = array("orderid" => 123456);
$postfields = json_encode($postfields);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST,1);
curl_setopt($curl, CURLOPT_POSTFIELDS,$postfields);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headerfields);
$result = curl_exec($curl);
curl_close($curl);
?>
命令行调用是这样的:
curl --header "Content-Type: application/json" --request POST --data "{"orderid":123456}" https://Mydomain/MyAPIEndPoint.php
端点正在读取通过此传递的 JSON:
$content = trim(file_get_contents("php://input"));
$decoded = (json_decode($content, true));
$orderid = $decoded['orderid'];
PHP Curl POST 工作正常,但命令行版本返回警告
Trying to access array offset on null
- 这表明该参数未设置,因此我的端点代码未读取该参数。
这样做的目的是能够构建命令行 CuRL 命令,以便我可以通过
exec()
语句将其作为“即发即忘”调用提交。
JSON 中的双引号与分隔参数的双引号匹配。要么转义嵌套双引号:
--data "{\"orderid\":123456}"
或使用不同的分隔符:
--data '{"orderid":123456}'