Dropbox API令牌验证

时间:2015-12-12 05:12:20

标签: dropbox-api

这个问题来自我的previous one。我以为我会通过调用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;

该文档实际上并未表明有必要提供 Content-Type 标头。但是,如果没有该标题,我会收到消息

  

错误的HTTP“Content-Type”标题:“application / x-www-form-urlencoded”。期待“application / json”中的一个,......

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

  

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

只提供一些虚假的帖子数据curl_setopt($ch,CURL_POSTFIELDS,json_encode(array('a'=>1)));并没有采取任何措施来纠正这种情况。我做错了什么?

1 个答案:

答案 0 :(得分:2)

documentation并不表示预计有Content-Type标头,因为此端点不接受任何参数,因此不需要正文,因此&#39 ;没有内容可以通过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标头。但默认情况下,它显然会发送&#34; application / x-www-form-urlencoded&#34;,但API并未接受。如果你设置了一个&#34; application / json&#34;,那么API会尝试解释这样的身体,但是由于它不是有效的JSON,所以不能这样做,并且因此失败了。

omit the Content-Type header with curl in PHP显然不容易(或者可能不可能),所以替代方法是设置&#34; application / json&#34;,但提供有效的JSON,例如&# 34;空&#34 ;.以下是您的代码的修改版本:

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

?>
相关问题