在我使用 .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 对象,但没有成功。