[英]PHP cUrl not posting
我想使用cURL在php中發送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_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一個數組,因此,修復它所需的所有操作是從該行中刪除“數組”,例如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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.