将 POST curl 从命令行转换为 php 时遇到问题

2023-12-12

我在将curl 命令转换为php 时遇到问题。

这部分效果很好。

CURL 命令将条目添加到我的 Parse.com 数据库中:

curl -X POST \
  -H "X-Parse-Application-Id: my_id" \
  -H "X-Parse-REST-API-Key: api_id" \
  -H "Content-Type: application/json" \
  -d "{\"SiteID\":\"foundID\",\"dataUsedString\":\"foundUsage\",\"usageDate\":\"foundDate\", \"monthString\":\"foundMonth\", \"dayString\":\"foundDay\",\"yearString\":\"foundYear\"}" \
  https://api.parse.com/1/classes/MyClass

已解决的答案:

我创建了这个 php 脚本来复制命令:

   <?php 
   $ch = curl_init('https://api.parse.com/1/classes/MyClass');

curl_setopt($ch,CURLOPT_HTTPHEADER,
    array('X-Parse-Application-Id:my_id',
'X-Parse-REST-API-Key:api_id',
'Content-Type: application/json'));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"SiteID\":\"foundID\",\"dataUsedString\":\"foundUsage\",\"usageDate\":\"foundDate\", \"monthString\":\"foundMonth\", \"dayString\":\"foundDay\",\"yearString\":\"foundYear\"}");

curl_exec($ch);
curl_close($ch);
?>

您错过了一些关键配置。 这些是设置CURL使用POST发送请求,第二个是要发送的数据。 (原始数据作为字符串发送到 POSTFIELDS 中,如果您发送数组 - 它将自动附加标头“multipart/form-data”

$ch = curl_init('https://api.parse.com/1/classes/MyClass');

curl_setopt($ch,CURLOPT_HTTPHEADER,
  array(
    'X-Parse-Application-Id:my_id',
    'X-Parse-REST-API-Key:api_id',
    'Content-Type: application/json'
  )
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"SiteID\":\"foundID\",\"dataUsedString\":\"foundUsage\",\"usageDate\":\"foundDate\", \"monthString\":\"foundMonth\", \"dayString\":\"foundDay\",\"yearString\":\"foundYear\"}");
curl_exec($ch);
curl_close($ch);

HTH:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 POST curl 从命令行转换为 php 时遇到问题 的相关文章