diff options
author | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-07-01 20:51:15 +0200 |
---|---|---|
committer | TheArcaneBrony <myrainbowdash949@gmail.com> | 2023-07-01 20:51:15 +0200 |
commit | 7978f08235ceca22eacae11a88a7703513238cb3 (patch) | |
tree | 6a7058f21f6040cc1e9396a85774bc16ea133c9e /MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs | |
parent | Todays progress (diff) | |
download | MatrixUtils-7978f08235ceca22eacae11a88a7703513238cb3.tar.xz |
Deduplicate some api calls
Diffstat (limited to 'MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs')
-rw-r--r-- | MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs | 13 |
1 files changed, 12 insertions, 1 deletions
diff --git a/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs b/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs index 852e1d8..060867d 100644 --- a/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs +++ b/MatrixRoomUtils.Core/Extensions/HttpClientExtensions.cs @@ -1,3 +1,4 @@ +using System.Net.Http.Headers; using System.Reflection; using System.Text.Json; @@ -19,6 +20,7 @@ public static class HttpClientExtensions { public class MatrixHttpClient : HttpClient { public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + Console.WriteLine($"Sending request to {request.RequestUri}"); try { HttpRequestOptionsKey<bool> WebAssemblyEnableStreamingResponseKey = new HttpRequestOptionsKey<bool>("WebAssemblyEnableStreamingResponse"); @@ -35,10 +37,10 @@ public class MatrixHttpClient : HttpClient { } var a = await base.SendAsync(request, cancellationToken); if (!a.IsSuccessStatusCode) { - Console.WriteLine($"Failed to send request: {a.StatusCode}"); var content = await a.Content.ReadAsStringAsync(cancellationToken); if (content.StartsWith('{')) { var ex = JsonSerializer.Deserialize<MatrixException>(content); + Console.WriteLine($"Failed to send request: {ex}"); if (ex?.RetryAfterMs is not null) { await Task.Delay(ex.RetryAfterMs.Value, cancellationToken); typeof(HttpRequestMessage).GetField("_sendStatus", BindingFlags.NonPublic | BindingFlags.Instance)?.SetValue(request, 0); @@ -50,4 +52,13 @@ public class MatrixHttpClient : HttpClient { } return a; } + // GetFromJsonAsync + public async Task<T> GetFromJsonAsync<T>(string requestUri, CancellationToken cancellationToken = default) { + var request = new HttpRequestMessage(HttpMethod.Get, requestUri); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + var response = await SendAsync(request, cancellationToken); + response.EnsureSuccessStatusCode(); + await using var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken); + return await JsonSerializer.DeserializeAsync<T>(responseStream, cancellationToken: cancellationToken); + } } \ No newline at end of file |