Dropbox HTTP API - PHP cURL 自动添加 header 项目边界

Dropbox HTTP API - PHP cURL added header item boundary automatically

我是 Dropbox API 集成的新手,我正在使用 PHP cURL 扩展来调用 HTTP REST API,当我尝试发出请求我收到以下字符串:

Error in call to API function "files/list_folder": 
Bad HTTP "Content-Type" header: 
"text/plain; boundary=----------------------------645eb1c4046b". 
Expecting one of "application/json", "application/json; charset=utf-8", 
"text/plain; charset=dropbox-cors-hack".

我发送的代码与此非常相似:

$sUrl = "https://api.dropboxapi.com/2/files/list_folder";
$oCurl = curl_init($sUrl);
$aPostData = array('path' => '', 'recursive' => true, 'show_hidden' => true);
$sBearer = "MY_TOKEN";
$aRequestOptions = array(
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain',
            'Authorization: Bearer ' . $sBearer),
        CURLOPT_POSTFIELDS => $aPostData,
        CURLOPT_RETURNTRANSFER => true);
curl_setopt_array($aRequestOptions);
$hExec = curl_exec($oCurl);
if ($hExec === false){
    // Some error info in JSON format
} else {
    var_dump($hExec);
}

如您所见,您正在执行多部分表单上传,这不是 API 所期望的。

您需要做一些不同的事情:

  • 您应该在正文中将参数作为 JSON 发送。
  • 您应该相应地将 Content-Type 设置为 application/json
  • /files/list_folder 上没有 show_hidden 参数,但也许您打算发送 include_deleted
  • curl_setopt_array method 有两个参数,第一个应该是 curl 句柄。

这是适合我的代码的更新版本:

<?php

$sUrl = "https://api.dropboxapi.com/2/files/list_folder";
$oCurl = curl_init($sUrl);
$aPostData = array('path' => '', 'recursive' => true, 'include_deleted' => true);
$sBearer = "MY_TOKEN";
$aRequestOptions = array(
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => array('Content-Type: application/json',
            'Authorization: Bearer ' . $sBearer),
        CURLOPT_POSTFIELDS => json_encode($aPostData),
        CURLOPT_RETURNTRANSFER => true);
curl_setopt_array($oCurl, $aRequestOptions);
$hExec = curl_exec($oCurl);
if ($hExec === false){
    // Some error info in JSON format
} else {
    var_dump($hExec);
}

?>