Skip to content

Instantly share code, notes, and snippets.

@spencerkittleson
Created August 21, 2023 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spencerkittleson/20e9c07124d94bf9cd5efae51ef71b19 to your computer and use it in GitHub Desktop.
Save spencerkittleson/20e9c07124d94bf9cd5efae51ef71b19 to your computer and use it in GitHub Desktop.
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