Created
August 21, 2023 22:00
-
-
Save spencerkittleson/20e9c07124d94bf9cd5efae51ef71b19 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public async Task<DataResponse> GetAsync(string uri, List<KeyValuePair<string, string>> formValues) { | |
try { | |
var auth = new AuthenticationHeaderValue("Basic", | |
Convert.ToBase64String(Encoding.UTF8.GetBytes( | |
$"{HttpUtility.UrlEncode(_clientId)}:{HttpUtility.UrlEncode(_clientSecret)}"))); | |
var request = new HttpRequestMessage(HttpMethod.Post, uri) { | |
Headers = { Authorization = auth }, | |
Content = new FormUrlEncodedContent(formValues) | |
}; | |
using var response = await HttpClient.SendAsync(request); | |
var content = await response?.Content?.ReadAsStringAsync() ?? ""; | |
if(!response.IsSuccessStatusCode) { | |
LogWarn($"Request: {request} {await request.Content.ReadAsStringAsync()}"); | |
LogWarn($"Response: {response} - {response.StatusCode} - {response.ReasonPhrase}: {content}"); | |
} | |
response.EnsureSuccessStatusCode(); | |
if(string.IsNullOrEmpty(content)) { | |
throw new ArgumentNullException(nameof(content)); | |
} | |
return JsonSerializer.Deserialize<DataResponse>(content); | |
} | |
catch(Exception ex) { | |
var errorValueBuilder = new StringBuilder(); | |
foreach(var kv in formValues) { | |
errorValueBuilder.AppendLine($"{kv.Key}:{kv.Value}"); | |
} | |
LogWarn(errorValueBuilder.ToString()); | |
LogError(ex); | |
throw; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment