使用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,然后发送对应的请求就好啦,灰常的简单。

posted @   霖雨  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 从 Windows Forms 到微服务的经验教训
· 李飞飞的50美金比肩DeepSeek把CEO忽悠瘸了,倒霉的却是程序员
历史上的今天:
2017-11-25 SharePoint Online 创建资产库
2015-11-25 SharePoint 2013 Error - File names can't contain the following characters: & " ? < > # {} % ~ / \.
点击右上角即可分享
微信分享提示