使用PHP CURL将参数丢失或不作为JSON数组发送

时间:2013-04-03 19:30:47

标签: php json curl

错误:

{"jsonrpc":"2.0","id":0,"error":{"code":1,"message":"Parameters missing or not sent as an JSON array. "}}

我的代码:

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Accept: text/plain, */*; q=0.01")); 
curl_setopt($ch, CURLOPT_URL, 'http://example.com/rpc/ClientApi?_session=XX');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('method' => 'AdsApi.giveAdLifeByCategory','params' => '["Ads4Life"]', 'id' => '0')));
curl_setopt($ch, CURLOPT_POST, 1); 
$result = curl_exec($ch);

?>

我正在尝试模仿此请求:

[{"method":"AdsApi.giveAdLifeByCategory","params":["Ads4Life"],"id":0}]

正确答复:

[{
     "jsonrpc": "2.0",
     "id": 0,
     "result": {
         "status": true,
         "timeStamp": 0
     }
}]

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

错误的包围:

... 'AdsApi.giveAdLifeByCategory','params' => '["Ads4Life"]', 'id' => '0')));
                                               ^---       ^--

你的“模拟”样本有围绕它的大括号,但你将它们嵌入到数组键定义中,所以当生成JSON时,它实际上是:

... "params": "[\"Ads4Life\"]" ...

在字符串中嵌入[""]

可能只是

... 'AdsApi.giveAdLifeByCategory','params' => array('Ads4Life'), 'id' => '0')));
                                                   ^^^^^^^^^^