94 lines
3.4 KiB
C#

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
namespace Marco.Pms.UtilityApplication
{
internal class ApiService
{
private readonly HttpClient _httpClient;
private readonly string _apiUrl;
public ApiService(string apiUrl)
{
_httpClient = new HttpClient();
_apiUrl = apiUrl;
}
public async Task<bool> SendDataAsync<T>(T data, string token)
{
try
{
var jsonContent = JsonConvert.SerializeObject(data);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = await _httpClient.PostAsync(_apiUrl, content);
response.EnsureSuccessStatusCode(); // Throws an exception if the HTTP response status is an error code.
string responseBody = await response.Content.ReadAsStringAsync();
// You can parse the responseBody if your API returns something useful
Console.WriteLine($"API Response: {responseBody}");
return true;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"API request error: {ex.Message}");
// Log or handle the error appropriately in your UI
return false;
}
catch (JsonException ex)
{
Console.WriteLine($"JSON serialization error: {ex.Message}");
return false;
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
return false;
}
}
public async Task<string> LoginAsync<T>(T data)
{
try
{
var jsonContent = JsonConvert.SerializeObject(data);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.PostAsync(_apiUrl, content);
response.EnsureSuccessStatusCode(); // Throws an exception if the HTTP response status is an error code.
string responseBody = await response.Content.ReadAsStringAsync();
// You can parse the responseBody if your API returns something useful
Console.WriteLine($"API Response: {responseBody}");
var jObject = JObject.Parse(responseBody);
string jwt = jObject["data"]?["token"]?.ToString() ?? string.Empty; ;
return jwt;
}
catch (HttpRequestException ex)
{
Console.WriteLine($"API request error: {ex.Message}");
// Log or handle the error appropriately in your UI
return string.Empty;
}
catch (JsonException ex)
{
Console.WriteLine($"JSON serialization error: {ex.Message}");
return string.Empty;
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
return string.Empty;
}
}
}
}