简体   繁体   English

我在 c# wpf 中使用 spotify api 未经授权收到错误 401

[英]im getting a error 401 unauthorized using the spotify api in c# wpf

Im getting this Error.我收到此错误。 System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.' System.Net.WebException: '远程服务器返回错误:(401) 未经授权。' Code is provided below.下面提供了代码。

When i take out the method "PrintUsefulData(api)", everything seems to work fine that method has a http client webrequest.当我取出方法“PrintUsefulData(api)”时,似乎一切正常,该方法有一个 http 客户端 webrequest。 Im trying to request the following https://api.spotify.com/v1/albums .我试图请求以下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;
    }
}

} }

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 Token which should have been supplied at the point of authorisation to get a new Access Token .令牌到期- 如果您在请求中收到 401 错误,那么您需要使用Refresh Token ,该Refresh Token本应在授权点提供以获取新的Access Token This should apply to ANY call you make to the API.这应该适用于您对 API 进行的任何调用。

  • Request Parameters - The endpoint you're calling ( https://api.spotify.com/v1/albums ) requires the parameter ids so the Spotify API knows what 'albums' you would like to return.请求参数- 您正在调用的端点 ( https://api.spotify.com/v1/albums ) 需要参数ids因此 Spotify API 知道您想要返回什么“专辑” More info: https://developer.spotify.com/documentation/web-api/reference/albums/get-several-albums/更多信息: https://developer.spotify.com/documentation/web-api/reference/albums/get-several-albums/ : https://developer.spotify.com/documentation/web-api/reference/albums/get-several-albums/

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.另一件事要检查: -范围- 确保在对 API 进行身份验证时,您正在设置将来执行操作所需的范围。 I don't think this applies specifically in this case but worth noting.我认为这不适用于这种情况,但值得注意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 httpclient api 在 c# 中出现未经授权的 401 错误 - httpclient api unauthorized 401 error in c# 使用C#发布Apple News API的文章-(401)未经授权 - Publish article for Apple news API using C# - (401) Unauthorized 出现错误:远程服务器返回错误:(401)未经授权。 ,同时将我的网站评论发布到Twitter。 使用C# - Getting error : The remote server returned an error: (401) Unauthorized. , while posting my website comments to twitter. Using C# 链接到C#中的当前状态更新,获取错误(401)未经授权 - Linked In current-status update in c#, Getting Error (401) Unauthorized 从我的C#应用​​程序访问webDav文件夹时出现401未经授权的错误? - Getting 401 unauthorized error while accessing webDav folder from my C# application? 在C#窗口应用程序中SSRS报告呈现中出现错误:请求失败,HTTP状态为401:未经授权 - Getting Error in SSRS report rendering in C# window application: The request failed with HTTP status 401: Unauthorized 在将Hammock与Tumblr API结合使用以检索喜欢项时,为什么会出现此401未经授权的错误? - Why am I getting this 401 unauthorized error while using Hammock with the Tumblr API to retrieve likes? c# - Exchange Web Service API和401未经授权的例外 - c# - Exchange Web Service API and 401 unauthorized exception HP ALM 12.21 REST API - 401 未经授权 - C# - HP ALM 12.21 REST API - 401 Unauthorized - C# asp.net c#Google api文档-401未经授权 - asp.net c# google api Documents - 401 Unauthorized
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM