PHP cUrl not posting



我想在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 个错误

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_replate似乎刚刚插入到JSON Raw中。 如果您的$message_to_repred包含"',会发生什么情况? 它将使 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提供了一个数组,因此,修复它所需要的只是从该行中删除"数组",就像curl_setopt($ch, CURLOPT_POSTFIELDS,$jsonDataEncoded);

试试这个;

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 ) ) )

经过所有尝试,答案如下:

$jsonData = '{
"recipient":{
    "id":"'.$sender.'"
},
"message":{
    "text":"'.$message_to_reply.'"
}
}';
$jsonDataEncoded = $jsonData;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Here i removed the array//
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// By default in PHP7 CURL_SSL_VERIFYPEER, is true. You have to make it false//
$result = curl_exec($ch);

最新更新