首页 > 解决方案 > How to upload/download a file with Microsoft graph API in Unity3d

问题描述

I was able to make a oauth 2 login with Unity3d on Microsoft graph, I requested this permission for my app: https://graph.microsoft.com/files.readwrite.appfolder

After the usual code flow (redirect to url, permission from user, auth code exchanged for token code and token for bearer auth code) I was able to log in.

Problem is that the upload of small files does not work: https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content

I think this is the best I can do:

string myData = File.ReadAllText(Application.persistentDataPath + "/" + "provaupload.json");
    using (UnityWebRequest www = UnityWebRequest.Post("https://graph.microsoft.com/v1.0/me/drive/root:/AppTry/provaupload.json:/createUploadSession", myData)) {
        www.SetRequestHeader("Authorization", "Bearer <code>");
        www.SetRequestHeader("Content-Type", "application/json");
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError) {
            Debug.Log(www.error + " " + www.downloadHandler.text);
        } else {
            Debug.Log("Upload complete! " + www.downloadHandler.text);
        }
    }

and I get this error:

Generic/unknown HTTP error {
  "error": {
  "code": "BadRequest",
  "message": "Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format.",
  "innerError": {
    "request-id": "id",
    "date": "2018-07-20T06:24:30"
  }
}

I also tried the WWW class or Put instead of Post but I get "invalid API". Maybe my problem is in the base url: https://graph.microsoft.com/v1.0/me

or maybe it's in the path root:/AppTry/provaupload.json

or maybe in the permission.

I don't really know.

If you know how to make a Rest call with Microsoft Graph and One drive (even not in unity3d and even if you don't know how to solve my specific problem) it would be great to get some example.

标签: c#unity3duploadmicrosoft-graph-api

解决方案


要上传文件,请使用UploadHandler. 您还必须将字符串编码为UTF8. 正如您在评论部分提到的,看起来您必须使用PUT而不是,POST并且应该将 url 更改为其他内容。

更像这样的东西:

string myData = File.ReadAllText(Application.persistentDataPath + "/" + "provaupload.json");
string url = "https://graph.microsoft.com/v1.0/me/drive/root:/AppTry/provaupload.json:/content";

using (UnityWebRequest www = new UnityWebRequest(url, "PUT"))
{
    byte[] dataToSend = new System.Text.UTF8Encoding().GetBytes(myData);
    www.uploadHandler = (UploadHandler)new UploadHandlerRaw(dataToSend);
    www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();

    www.SetRequestHeader("Authorization", "Bearer <code>");
    www.SetRequestHeader("Content-Type", "application/json");
    yield return www.SendWebRequest();

    if (www.isNetworkError || www.isHttpError)
    {
        Debug.Log(www.error + " " + www.downloadHandler.text);
    }
    else
    {
        Debug.Log("Upload complete! " + www.downloadHandler.text);
    }
}

推荐阅读