我正试图使用phpccurl从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"]}'
谢谢!
最佳答案
你很接近,但有几个小错误。
首先,虽然您确实正确地指定了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将您的请求视为内容类型为application/x-www-form-urlencoded
的表单帖子。这将产生一个问题,因为SurveyMonkey需要内容类型application/json
。删除此:
curl_setopt($ch, CURLOPT_POST, true);
换成这个:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");