Dropbox API令牌验证



这个问题是我上一个问题的延续。我想通过调用get_space_usage API函数来执行基本的令牌身份验证。我试过

 $headers = array("Authorization: Bearer  token",
                 "Content-Type:application/json");
 $ch = curl_init('https://api.dropboxapi.com/2/users/get_space_usage/');
 curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
 curl_setopt($ch,CURLOPT_POST,true);
 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
 $response = curl_exec($ch);
 curl_close($ch);
 echo $response;

事实上,文档并没有表明有必要提供内容类型标题。然而,如果没有这个标题,我会得到消息

错误的HTTP"内容类型"标头:"application/x-www-form-urlencoded"。应为"application/json"之一,。。。

放入该标头但不提供POST字段会产生另一个错误

请求正文:无法将输入解码为JSON

仅仅提供一些伪后期数据curl_setopt($ch,CURL_POSTFIELDS,json_encode(array('a'=>1)));并不能补救这种情况。我做错了什么?

文档没有指出需要Content-Type标头,因为由于该端点不接受任何参数,因此不需要正文,因此没有内容可以通过Content-Type标头进行描述。下面是一个工作命令行curl示例,根据文档:

curl -X POST https://api.dropboxapi.com/2/users/get_space_usage 
    --header "Authorization: Bearer <ACCESS_TOKEN>"

在PHP中将其转换为curl需要确保PHP也不会发送Content-Type头。默认情况下,它显然发送"application/x-www-form-urlencoded",但API不接受这一点。如果您设置了"application/json",API将尝试将主体解释为这样,但无法这样做,因为它不是有效的json,因此相应地失败。

在PHP中用curl省略Content-Type头显然不容易(或者可能不可能),因此另一种选择是设置"application/json",但提供有效的json,例如"null"。以下是您代码的修改版本:

<?php
$headers = array("Authorization: Bearer <ACCESS_TOKEN>",
                 "Content-Type: application/json");
$ch = curl_init('https://api.dropboxapi.com/2/users/get_space_usage');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "null");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>

最新更新