PHP cUrl没有发布

时间:2017-01-17 07:18:59

标签: php curl post

我想在php中使用cURL发送json数据,但问题是cURL没有发布任何数据。

注意:已正确安装和配置cURL。

$ch = curl_init($url);
//The JSON data.
$jsonData = '{
    "recipient":{
    "id":"'.$sender.'"
},
"message":{
    "text":"'.$message_to_reply.'"
}
}';


$jsonDataEncoded = $jsonData;

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, array($jsonDataEncoded));

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_exec($ch);

json数据工作正常,但是cURL帖子没有发布任何内容,也没有提供任何类型的警告/通知或错误。

3 个答案:

答案 0 :(得分:1)

据我所知,你犯了3个错误

1:不要curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");,告诉curl你想要POST请求的正确方法是curl_setopt($ch, CURLOPT_POST, true);

2:当你给CURLOPT_POSTFIELDS一个数组时,它实际上转换为multipart/form-data编码,这不是你想要的(你想传输一个json)

3:您的$ sender和$ message_to_reply似乎只是插入到json raw中。如果您的$ message_to_reply包含"',会发生什么?它将使json无效。考虑正确编码,例如使用json_encode,如

$jsonData = array (
        'recipient' => array (
                'id' => $sender 
        ),
        'message' => array (
                'text' => $messaage_to_reply 
        ) 
);
$jsonDataEncoded = json_encode ( $jsonData, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );

但是,如果$ sender和$ message_to_reply已经正确进行了json编码,那么就我所知,原始代码无法工作的唯一原因是你给CURLOPT_POSTFIELDS一个数组,因此,所有这些& #39;需要修复它就是删除" array"从该行开始,如curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonDataEncoded);

答案 1 :(得分:0)

试试这个;

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(json_decode($jsonDataEncoded)));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

您可能不想将所有数据传递给一个密钥。


输出print_r(array($jsonDataEncoded))

Array ( [0] => { "recipient":{ "id":"me" }, "message":{ "text":"hello" } } ) 


print_r(json_decode(array($jsonDataEncoded)))

的输出
Array ( [0] => stdClass Object ( [recipient] => stdClass Object ( [id] => me ) [message] => stdClass Object ( [text] => hello ) ) )

答案 2 :(得分:0)

经过一切尝试,这就是答案:

main