我正在努力从Spotify API获取访问令牌,但我无法检索它。我在获取授权代码并完成整个过程后尝试获取500内部服务器错误。这是我的代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace SpotifyAPI
{
public partial class Callback : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string code = Request.QueryString["code"];
string state = Request.QueryString["state"];
// Generate URL with authorization code
string url = "https://accounts.spotify.com/api/token?grant_type=authorization_code&code=" + code + "&redirect_uri=http://localhost:64270/Callback.aspx";
// get Client ID and Secret
string clientId = ((Site1)this.Master).getClientId();
string clientSecret = ((Site1)this.Master).getClientSecret();
// generate encoded header string for token request
string preAuthorizationCode = clientId + ":" + clientSecret;
string postAuthorizationCode = Base64Encode(preAuthorizationCode);
Debug.WriteLine("Post Authorization Code is: " + postAuthorizationCode);
var webrequest = (HttpWebRequest)WebRequest.CreateHttp(url);
webrequest.Method = "POST";
WebHeaderCollection myWebHeaderCollection = webrequest.Headers;
myWebHeaderCollection.Add("Authorization: Basic " + postAuthorizationCode);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)webrequest.GetResponse();
Stream responseStream = myHttpWebResponse.GetResponseStream();
var reader = new StreamReader(responseStream);
string result = reader.ReadToEnd();
}
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
}
}
感谢任何帮助。谢谢!
答案 0 :(得分:0)
如文档中所述
https://developer.spotify.com/web-api/authorization-guide/
你必须发送
“grant_type”,“code”和“redirect_uri”参数作为POST正文。您将它们作为url参数发送,因此Spotify会出错。