public static string GetAccessToken() { SpotifyToken token = new SpotifyToken(); string postString = string.Format("grant_type=client_credentials"); byte[] byteArray = Encoding.UTF8.GetBytes(postString); string url = "https://accounts.spotify.com/api/token"; WebRequest request = WebRequest.Create(url); request.Method = "POST"; request.Headers.Add("Authorization", "Basic NDQxODA1ZDE4MDAyNDNlZGI2MjVjOGRkMzE0M2MzMjc6NjQ0MDMzZThlMGFkNDY0YmI3MGJmOWExN2Y2MjJiYmE="); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; string response = getResponse(request); try { token = JsonConvert.DeserializeObject<SpotifyToken>(response); return token.access_token; } catch (Exception) { return ""; } }
// Static Methods // /// <summary> /// Gets a Spotify access token as a string from the given encoded Client ID + Secret /// Credit to Hendrik Bulens: https://hendrikbulens.com/2015/01/07/c-and-the-spotify-web-api-part-i/ /// </summary> /// <param name="encodedClientIDAndSecret"></param> /// <returns>A task for asynchronous operation, which returns a Spotify Access Token as a string</returns> public static async Task <string> GetAccessTokenAsStringAsync(string encodedClientIDAndSecret) { SpotifyToken token = new SpotifyToken(); string postString = "grant_type=client_credentials"; byte[] postStringAsBytes = Encoding.UTF8.GetBytes(postString); string tokenUrl = "https://accounts.spotify.com/api/token"; WebRequest request = WebRequest.Create(tokenUrl); request.Method = "POST"; request.Headers.Add("Authorization", $"Basic {encodedClientIDAndSecret}"); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postStringAsBytes.Length; using Stream dataStream = request.GetRequestStream(); dataStream.Write(postStringAsBytes, 0, postStringAsBytes.Length); using WebResponse response = await request.GetResponseAsync(); using Stream responseStream = response.GetResponseStream(); using StreamReader reader = new StreamReader(responseStream); string responseFromServer = reader.ReadToEnd(); token = JsonConvert.DeserializeObject <SpotifyToken>(responseFromServer); return(token.access_token); }