【问题标题】:How to PHP cURL to SurveyMonkey API?如何 PHP cURL 到 SurveyMonkey API?
【发布时间】:2015-06-18 23:57:54
【问题描述】:

我正在尝试使用 PHP cURL 从 SurveyMonkey 的 API 中检索一些数据,但一直收到 500 错误。

这是我的代码:

  $requestHeaders = array(
    'Content-Type: application/json',
    'Authorization: Bearer ' . $accessToken,
  );

  $baseUrl = 'https://api.surveymonkey.net';
  $endpoint = '/v2/surveys/get_survey_list?api_key=XXXXXXXXXXXXXX';

  $fields = array(
    'fields' => array(
      'title','analysis_url','date_created','date_modified'
    )
  );

  $fieldsString = json_encode($fields);

  $ch  = curl_init();
  curl_setopt($ch, CURLOPT_URL, $baseUrl . $endpoint);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsString);

  $result = curl_exec($ch);

  curl_close($ch);

我得到的回应是

{
    "status": 500,
    "request_id": "e0c10adf-ae8f-467d-83af-151e8e229618",
    "error": {
        "message": "Server busy, please try again later."
    }
}

这在命令行上完美运行:

curl -H 'Authorization:bearer XXXXX' 
     -H 'Content-Type: application/json' https://api.surveymonkey.net/v2/surveys/get_survey_list/?api_key=XXXXXXXX 
--data-binary '{"fields":["title","analysis_url","date_created","date_modified"]}'

谢谢!

【问题讨论】:

  • 我不确定我们能否帮助您解决 500 错误。您联系过 Surveymonkey 吗?
  • 我没有。由于我的命令行 curl 工作,我认为我做错了 php cURL

标签: php http curl surveymonkey


【解决方案1】:

你很接近,但有几个小错误。

首先,虽然您确实正确指定了Content-Type (application/json),但您还没有指定Content-Length

将此更改为 $requestHeaders 并将其移至 $fieldsString 的创建下方:

$requestHeaders = array(
     'Content-Type: application/json',
     'Authorization: Bearer ' . $_GET['code'],
     'Content-Length: ' . strlen($fieldsString)
);

其次,您已将 CURLOPT_POST 设置为 true。这将强制 CURL 将您的请求视为 form POST,其内容类型为 application/x-www-form-urlencoded。这会产生问题,因为 SurveyMonkey 期望内容类型为 application/json

删除这个:

curl_setopt($ch, CURLOPT_POST, true);

并将其替换为:

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

【讨论】:

  • 谢谢,但不幸的是这并没有解决它。 :\ 我最终使用了 exec() 并传递了我在终端上输入的巨大字符串,但这不是一个非常干净的解决方案。请让我知道您是否可以想到其他任何事情。谢谢!
  • 其实你的答案是正确的。我刚刚意识到我错过了将代码交换为访问令牌的步骤。非常感谢!
猜你喜欢
  • 2015-12-31
  • 1970-01-01
  • 2016-07-17
  • 2021-11-12
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
相关资源
最近更新 更多