問題描述
如何使用 Rest api 和 oauth2.0 創建文件夾和上傳文件 (How to create folder and upload file using Rest api and oauth2.0)
I want to create a folder and upload files using rest api my code is like this
public string CreateFolder(string FolderName)
{
int WorkSpaceId = 330201;
int id = 168079105;
var queryString = HttpContext.Current.Session["tokenSession"];
var request = WebRequest.Create(RequestProfileUrl + FolderName);
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
request.Headers.Add("Authorization", "Bearer " + AccessToken);
request.ContentType = "multipart/form‑data";
request.Method = "POST";
var response = request.GetResponse();
HttpContext.Current.Response.Redirect("" + request.RequestUri);
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var responseText = reader.ReadToEnd();
reader.Close();
return responseText;
}
}
I have to do like this
POST https://apis.live.net/v5.0/me/skydrive
Authorization: Bearer ACCESS_TOKEN
Content‑Type: multipart/form‑data
{
"name": "My example folder"
}`
I added request header and content‑type, I don't know how to add name
parameter to my request.
參考解法
方法 1:
To write the body of your POST request you need to get the request stream first, and then write to it. See the sample code below. Note that I changed the Content‑Type from "multipart/form‑data" to "application/json" as this is what your data seems to be.
// String with the body content
string postBody = "{\"name\":\"myfoldername\"}";
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postBody);
// Set Content type to application/json
myHttpWebRequest.ContentType = "application/json";
// Set content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;
// Get the request stream and write body bytes to it
Stream newStream = myHttpWebRequest.GetRequestStream ();
newStream.Write (byte1, 0, byte1.Length);
(by user2322397、Federico Raggi)