【问题标题】:Spotify API - Getting 406 Unacceptable On Token Request When Using HttpRequestMessageSpotify API - 使用 HttpRequestMessage 时令牌请求出现 406 不可接受
【发布时间】:2019-10-16 14:48:36
【问题描述】:

在我使用 .NET 的 HttpRequestMessage 向 Spotify 的“获取令牌”端点发出的请求中,我收到了 406(不可接受)响应。

这是我的发布方法(仅供参考,这不是优化的代码——更多的是概念证明):

        public static async Task<string> PostForm(HttpClient httpClient, string url, List<KeyValuePair<string, string>> nameValueList)
        {
            using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, url))
            {
                httpRequest.Content = new FormUrlEncodedContent(nameValueList);
                using (var response = await httpClient.SendAsync(httpRequest))
                {
                    response.EnsureSuccessStatusCode();
                    return await response.Content.ReadAsStringAsync();
                }
            }
        }

我用这个来调用那个方法:

        public Token GetSpotifyToken()
        {
            var httpClient= new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
            httpClient.DefaultRequestHeaders.Add("Authorization", "Basic MyApiCredsBase64EncodedYesIveConfirmedTheseWork=");

            var url = "https://accounts.spotify.com/api/token";
            var grantType = new KeyValuePair<string, string>("grant_type", "client_credentials");

            return JsonConvert.DeserializeObject<Token>
                (ApiRequest.PostForm(postClient, url,
                new List<KeyValuePair<string, string>>() { grantType } )
                .GetAwaiter()
                .GetResult());
        }

我知道这个问题与 grant_type=client_credentials 如何添加到请求中有关。这种使用 RestSharp 的方法效果很好:

        public Token GetSpotifyToken()
        {
            var client = new RestClient("https://accounts.spotify.com/api/token");
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Authorization", "Basic MyApiCredentialsBase64Encoded=");
            request.AddParameter("undefined", "grant_type=client_credentials", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            return JsonConvert.DeserializeObject<Token>(response.Content);
        }

但我尝试通过几种不同的方式将grant_type=client_credentials 添加到 HttpRequestMessage 对象,但均未成功。

【问题讨论】:

    标签: c# .net .net-core spotify


    【解决方案1】:

    在我发布这个之后就想通了。

    在上面的代码中,一行...

    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
    

    ...导致问题。省略它允许代码工作。

    【讨论】:

      猜你喜欢
      • 2016-06-23
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2017-12-24
      • 2014-12-24
      相关资源
      最近更新 更多