Я получаю эту ошибку.System.Net.WebException: «Удаленный сервер возвратил ошибку: (401) Несанкционированный.»Код приведен ниже.
Когда я убираю метод «PrintUsefulData (api)», кажется, что все работает нормально, у этого метода есть веб-запрос клиента http.Я пытаюсь запросить следующее https://api.spotify.com/v1/albums.
static void Main(string[] args)
{
_clientId = string.IsNullOrEmpty(_clientId)
? Environment.GetEnvironmentVariable("my_clientId")//my id
: _clientId;
_secretId = string.IsNullOrEmpty(_secretId)
? Environment.GetEnvironmentVariable("my_secretId") // my id
: _secretId;
AuthorizationCodeAuth auth =
new AuthorizationCodeAuth(_clientId, _secretId, "http://localhost:5002", "http://localhost:5002", Scope.PlaylistReadPrivate | Scope.PlaylistReadCollaborative);
auth.AuthReceived += AuthOnAuthReceived;
auth.Start();
auth.OpenBrowser();
Console.ReadLine();
auth.Stop(0);
}
private static async void AuthOnAuthReceived(object sender,
AuthorizationCode payload)
{
AuthorizationCodeAuth auth = (AuthorizationCodeAuth)sender;
auth.Stop();
Token token = await auth.ExchangeCode(payload.Code);
SpotifyWebAPI api = new SpotifyWebAPI
{
AccessToken = token.AccessToken,
TokenType = token.TokenType
};
PrintUsefulData(api);
}
private static async void PrintUsefulData(SpotifyWebAPI api)
{
RestClient rClient = new RestClient();
rClient.endPoint = "https://api.spotify.com/v1/albums";
string strResponse = string.Empty;
strResponse = rClient.getRequest();
}
}
}
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
class RestClient
{
public string endPoint { get; set; }
public HttpVerb httpMethod { get; set; }
public RestClient()
{
endPoint = string.Empty;
httpMethod = HttpVerb.GET;
}
public string getRequest()
{
string strResponseVal = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new ApplicationException("error code: " + response.StatusCode);
}
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseVal = reader.ReadToEnd();
}
}
}
}
return strResponseVal;
}
}
}