using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace AntDesign.core.Extensions { internal static class HttpClientExtensions { public static async Task GetFromJsonAsync(this HttpClient client, string requestUri, CancellationToken cancellationToken = default) { if (client == null) { throw new ArgumentNullException(nameof(client)); } var res = await client.GetAsync(requestUri, cancellationToken); if (res.IsSuccessStatusCode) { var utf8Json = await res.Content.ReadAsByteArrayAsync(Encoding.UTF8); return JsonSerializer.Deserialize(utf8Json, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, }); } return default; } /// /// Reads as a binary array and converts to the specified encoding /// /// /// The target encoding /// /// private static async Task ReadAsByteArrayAsync(this HttpContent httpContent, Encoding dstEncoding) { var encoding = httpContent.GetEncoding(); var byteArray = await httpContent.ReadAsByteArrayAsync().ConfigureAwait(false); return encoding.Equals(dstEncoding) ? byteArray : Encoding.Convert(encoding, dstEncoding, byteArray); } /// /// Get encoding information from /// /// /// private static Encoding GetEncoding(this HttpContent httpContent) { var charSet = httpContent.Headers.ContentType?.CharSet; if (string.IsNullOrEmpty(charSet) == true) { return Encoding.UTF8; } var span = charSet.AsSpan().TrimStart('"').TrimEnd('"'); if (span.Equals(Encoding.UTF8.WebName, StringComparison.OrdinalIgnoreCase)) { return Encoding.UTF8; } return Encoding.GetEncoding(span.ToString()); } } }