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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

霖雨 - LinyuLoveTJ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值