繁体   English   中英

PHP cUrl不发布

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM