private async Task <HttpResponseMessage> PostOrPut(string verb, string url, object data, string accessToken = null) { Logger.Debug($"{verb} {url}. Token = {accessToken?.ToString()?.Substring(0, 4)}...", nameof(SpotifyWebApi)); _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken ?? (await GetAccessToken())); var content = data == null ? new StringContent("null") : new StringContent(JsonConvert.SerializeObject(data)); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = null; switch (verb) { case "PUT": response = await _http.PutAsync(url, content); break; case "POST": response = await _http.PostAsync(url, content); break; default: throw new NotSupportedException($"{verb} is not a supported verb"); } Logger.Information($"{verb} {url} {response.StatusCode}", nameof(RestHttpClient)); await RestHttpClient.CheckForErrors(response); return(response); }
/// <summary> /// Helper to PUT an object as JSON body /// </summary> protected internal virtual async Task <HttpResponseMessage> Put(string url, string userHash, object data) { // TODO: Could cause unusual effects if multiple threads mix client auth and user auth? _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", (await _userAccounts.GetUserAccessToken(userHash)).AccessToken); var content = new StringContent(JsonConvert.SerializeObject(data)); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = await _http.PutAsync(url, content); await RestHttpClient.CheckForErrors(response); return(response); }
public async Task CheckForErrors_SpotifyError_ThrowsSpotifyApiErrorException() { // arrange const string content = @"{ ""error"": { ""status"": 404, ""message"": ""No active device found"" } }"; var response = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(content, Encoding.Unicode, "application/json") }; // act await RestHttpClient.CheckForErrors(response); }