Im getting this Error. System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.' Code is provided below.
When i take out the method "PrintUsefulData(api)", everything seems to work fine that method has a http client webrequest. Im trying to request the following .
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, "", "", 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 = ""; 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; } } }
11 Answer
There could be a couple of things going on here but here's my shot at helping based on what code you've posted:
Token Expiration - If you get a 401 error on a request then you need to use the
Refresh Tokenwhich should have been supplied at the point of authorisation to get a newAccess Token. This should apply to ANY call you make to the API.Request Parameters - The endpoint you're calling (
) requires the parameteridsso the Spotify API knows what 'albums' you would like to return. More info:
Another thing to check: - Scope - make sure when you Auth to the API you are setting the required scope you need to perform actions in the future. I don't think this applies specifically in this case but worth noting.