Setting Authorization Header of HttpClient

前端 未结 21 2179
粉色の甜心
粉色の甜心 2020-11-22 14:53

I have an HttpClient that I am using for a REST API. However I am having trouble setting up the Authorization header. I need to set the header to the token I received from d

21条回答
  •  轮回少年
    2020-11-22 15:33

    static async Task GetToken()
    {
            string clientId = "XXX";
            string clientSecret = "YYY";
            string credentials = String.Format("{0}:{1}", clientId, clientSecret);
    
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials)));
                List> requestData = new List>();
                requestData.Add(new KeyValuePair("grant_type", "client_credentials"));
                FormUrlEncodedContent requestBody = new FormUrlEncodedContent(requestData);
                var request = await client.PostAsync("https://accounts.spotify.com/api/token", requestBody);
                var response = await request.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject(response);
            }
        }
    

提交回复
热议问题