使用HttpClient获取Graph API Token
前言
最近,在使用Graph API,然后,用HttpClient调用。可能,很多人讲不是有Net版本的API么,为什么要用Http去请求?对于这个,我只想说,好玩而已。
正文
下面是核心的代码,使用HttpClient发送请求token
public async static Task<string> GetGraphToken(string body, string talentid) { using (HttpClient httpClient = new HttpClient()) { var content = new StringContent(body); try { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"https://login.microsoftonline.com/{talentid}/oauth2/v2.0/token"); request.Content = content; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); HttpResponseMessage response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); GraphToken token = JsonConvert.DeserializeObject<GraphToken>(responseBody); Console.WriteLine("Response: " + token.access_token); return token.access_token; } else { Console.WriteLine("Error: " + response.StatusCode); return string.Empty; } } catch (Exception e) { Console.WriteLine(e.Message.ToString()); Console.WriteLine(e.StackTrace.ToString()); return string.Empty; } } }
调用:
string talentid = "12345678-cbbc-42b5-9576-56cac3b3be72"; string clientid = "b99fe2a4-028e-469a-9a6a-d60c956f34ac"; string secret = "_C11S~asf23FDA23JIJLIMNLJI-3HQ4Koogav_"; string body = $"grant_type=client_credentials&client_id={clientid}&client_secret={secret}&scope=https://graph.microsoft.com/.default"; string token = GetGraphToken(body, talentid).Result;
这里是拿到token,后面再请求使用token,然后发送对应的请求就好啦,灰常的简单。
博文推荐: |
SharePoint 2013 WebPart 管理工具分享[开源] |
基于SharePoint 2013的论坛解决方案[开源] |
SharePoint 2013 学习基础系列入门教程 |
SharePoint 2013 图文开发系列之门教程 |
SharePoint Designer 学习系列入门教程 |
特:如果有SharePoint项目,欢迎邮件联系我,Email:linyu_s@163.com |