【问题标题】:Trouble converting POST curl from command line to php无法将 POST curl 从命令行转换为 php
【发布时间】:2014-09-05 23:02:51
【问题描述】:

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

这部分效果很好。

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

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

【问题讨论】:

  • 你从远程服务器得到什么响应?
  • 已解决!!!!谢谢@valentin 和 cOle2

标签: php post curl parse-platform


【解决方案1】:

您遗漏了一些关键配置。 这些是设置 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:)

【讨论】:

  • 我将更新后的代码按照您的建议进行了更新。我在上面编辑了我的代码,以便您可以看到它。一行仍未添加到我的数据库中。还有什么建议吗?
【解决方案2】:

由于您正在执行 POST 请求,因此您需要告诉 Curl 也这样做:

$postData = '{"SiteID":"foundID","dataUsedString":"foundUsage","usageDate":"foundDate", "monthString":"foundMonth", "dayString":"foundDay","yearString":"foundYear"}';

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

您可能还需要提供Content-Length 标头:

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

【讨论】:

  • 我编辑了我的代码和答案以添加我更新的代码。但是,仍然没有创建新行。 :(
猜你喜欢
  • 1970-01-01
  • 2019-06-04
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 1970-01-01
  • 2017-01-01
相关资源
最近更新 更多