【问题标题】:create folder with microsoft graph api使用 microsoft graph api 创建文件夹
【发布时间】:2017-06-22 10:48:30
【问题描述】:

我正在尝试使用 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数据是正确的,标题也是..

【问题讨论】:

    标签: php json microsoft-graph-api


    【解决方案1】:

    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(),它工作正常。

    【讨论】:

      【解决方案2】:

      正确的方法是使用“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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多