using System.Text; using Newtonsoft.Json; namespace BLL.Integracion_DGA { public class ApiService { private readonly HttpClient _httpClient; public ApiService(HttpClient httpClient) { _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient)); } public async Task GetApiResponseAsync(string apiUrl, Dictionary headers = null) { using (var httpClient = new HttpClient()) { // Configura la URL base httpClient.BaseAddress = new Uri(apiUrl); var request = new HttpRequestMessage(HttpMethod.Get, apiUrl); // Configura los encabezados personalizados si se proporcionan if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } // Realiza la solicitud con la solicitud personalizada try { var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { return await response.Content.ReadAsStringAsync(); } else { // Maneja errores aquí según sea necesario. Console.WriteLine($"Error en la solicitud: {response.StatusCode}"); throw new HttpRequestException($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); throw new Exception($"Error en la solicitud HTTP: {ex.Message}"); // Maneja la excepción según sea necesario } } } public async Task PostApiResponseAsync(string apiUrl, Dictionary headers = null, object data = null) { using (var httpClient = new HttpClient()) { try { httpClient.BaseAddress = new Uri(apiUrl); var request = new HttpRequestMessage(HttpMethod.Post, apiUrl); // Serializa el objeto data a JSON //string jsonData = JsonSerializer.Serialize(data); string jsonData = JsonConvert.SerializeObject(data); // Crea el contenido de la solicitud HTTP con el cuerpo JSON HttpContent contenido = new StringContent(jsonData, Encoding.UTF8, "application/json"); request.Content = contenido; // Configura los encabezados personalizados si se proporcionan if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, header.Value); } } // Realiza la solicitud POST HttpResponseMessage response = await httpClient.SendAsync(request); // Verifica si la solicitud fue exitosa if (response.IsSuccessStatusCode) { // Lee la respuesta como una cadena return await response.Content.ReadAsStringAsync(); } else { // La solicitud no fue exitosa, maneja el error según sea necesario Console.WriteLine($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); throw new HttpRequestException($"Error en la solicitud HTTP. Código de estado: {response.StatusCode}"); } } catch (Exception ex) { // Maneja excepciones si ocurren Console.WriteLine($"Error en la solicitud HTTP: {ex.Message}"); throw new Exception($"Error en la solicitud HTTP: {ex.Message}"); } } } } }