Reputation: 1542
In my requests to Spotify's "get token" endpoint using .NET's HttpRequestMessage, I'm getting a 406 (Unacceptable) response.
Here's my post method (fyi, this is not optimized code -- more of a proof of concept):
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();
}
}
}
I'm calling that method with this:
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());
}
I know that the issue is related to how grant_type=client_credentials
is getting added to the request. This method, which uses RestSharp, works fine:
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);
}
But I've tried adding grant_type=client_credentials
to the HttpRequestMessage object in a few different ways, without success.
Upvotes: 0
Views: 440
Reputation: 1542
Figured it out, right after I posted this.
In the above code, the line...
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
...was causing the problem. Omitting it allowed the code to work.
Upvotes: 1