我尝试使用microsoft graph API创建文件夹。在microsoft graph explorer中,一切正常,但我的php代码返回错误:
$name = 'newFolder'; $access_token = '123..';
$link = 'https://graph.microsoft.com/v1.0/me/drive/root/children';
$data = array(
"name" => $name,
"folder" => array()
);
$curl=curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_URL,$link);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($curl,CURLOPT_HEADER,false);
curl_setopt($curl,CURLOPT_HTTPHEADER, array('Authorization: Bearer '.$access_token, 'Content-Type: application/json'));
curl_setopt($curl,CURLOPT_POSTFIELDS, $data);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
$out = curl_exec($curl);
$codeCurl = curl_getinfo($curl,CURLINFO_HTTP_CODE);
curl_close($curl);
这是' $ out': 400 BadRequest的响应,无法读取JSON请求有效负载。请确保设置了Content-Type标头,并且有效负载是有效的JSON格式。我无法理解,有什么不对? json数据是正确的,标题也是..
答案 0 :(得分:0)
正确的方法是使用" json_encode()"以正确的格式放置数据。该文件夹的正确格式为$folderParameters = ["name" => $name, "folder" => ["childCount" => '0']];
(感谢Create folder on OneDrive with API)
正确的代码是:
$link = 'https://graph.microsoft.com/v1.0/me/drive/root/children';
$data = [
"name" => $name,
"folder" => ["childCount" => '0']
];
$headers = [
'Authorization: Bearer '.$access_token,
'Content-Type: application/json'
];
$curl=curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl,CURLOPT_URL,$link);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'POST');
curl_setopt($curl,CURLOPT_HEADER,false);
curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl,CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,0);
$out = curl_exec($curl);
$codeCurl = curl_getinfo($curl,CURLINFO_HTTP_CODE);
curl_close($curl);
答案 1 :(得分:0)
microsoft graph API documentation显示了以下创建文件夹的示例请求:
POST /me/drive/root/children
Content-Type: application/json
{
"name": "New Folder",
"folder": { },
"@microsoft.graph.conflictBehavior": "rename"
}
要获得请求的这一部分:"folder": { }
,您可以将"folder" => new stdClass()
放入$ data数组中,或保留此"folder" => array()
并使用json_encode($data, JSON_FORCE_OBJECT)
。如果使用JSON_FORCE_OBJECT,则所有数组都将被编码为对象。
我遇到了同样的问题,但是响应中的错误有所不同:有效负载中的属性文件夹的值与架构不匹配。我正在使用"folder" => new stdClass()
,它工作正常。