using System.Net; using System.Text; using System.Text.Json; using MauiApp.Core.Converter; using MauiApp.Core.RestClient.Contracts; namespace MauiApp.Core.RestClient; public abstract class ApiRestClient : IApiRestClient { public string BaseUrl { get; init; } public static readonly JsonSerializerOptions JsonSerializerOptions = new() { Converters = { new DateTimeConverter(), new NullableDateTimeConverter(), } }; public async Task Get(string url, IDictionary queryParams = null, HttpClient httpClient = null) { queryParams ??= new Dictionary(); var queryParamString = string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={kvp.Value}")); httpClient ??= new HttpClient(); httpClient.BaseAddress = new Uri(BaseUrl); T response = default; try { var content = await httpClient.GetStreamAsync($"{url}?{queryParamString}"); response = await JsonSerializer.DeserializeAsync(content, JsonSerializerOptions); } catch (Exception ex) { throw new Exception("Errore interno " + ex + response); } finally { httpClient.Dispose(); } return response; } public async Task Post(string url, object body, IDictionary queryParams = null, HttpClient httpClient = null) { queryParams ??= new Dictionary(); var queryParamString = string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={kvp.Value}")); httpClient ??= new HttpClient(); httpClient.BaseAddress = new Uri(BaseUrl); var jsonBody = JsonSerializer.Serialize(body, JsonSerializerOptions); var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); HttpResponseMessage response = await httpClient.PostAsync($"{url}?{queryParamString}", content); if (response.StatusCode != HttpStatusCode.OK) throw new Exception(response.ReasonPhrase); var jsonResponse = await response.Content.ReadAsStreamAsync(); var result = await JsonSerializer.DeserializeAsync(jsonResponse, JsonSerializerOptions); httpClient.Dispose(); return result; } }