88 lines
2.5 KiB
C#
88 lines
2.5 KiB
C#
using Newtonsoft.Json;
|
|
using System.Text;
|
|
|
|
namespace Wrapper_Api_SequentMicrosystems.Main
|
|
{
|
|
internal class ApiClient
|
|
{
|
|
private HttpClient _httpClient;
|
|
|
|
|
|
public ApiClient()
|
|
{
|
|
_httpClient = new HttpClient();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Get data with GET method
|
|
/// </summary>
|
|
/// <typeparam name="Type"> Waited type of data</typeparam>
|
|
/// <param name="Endpoint">String with API endpoint</param>
|
|
/// <returns>Requested Data</returns>
|
|
/// <exception cref="Exception">Error message</exception>
|
|
public async Task<Type?> GetData<Type>(string Endpoint)
|
|
{
|
|
string response = await _httpClient.GetStringAsync(Endpoint);
|
|
|
|
try
|
|
{
|
|
return JsonConvert.DeserializeObject<Type>(response);//await response.Content.ReadAsStringAsync());
|
|
}
|
|
catch (Exception ex) { }
|
|
{
|
|
throw new Exception("GetData deserialize error");
|
|
}
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
/// Send data to api with POST method
|
|
/// </summary>
|
|
/// <typeparam name="Type"></typeparam>
|
|
/// <param name="Endpoint">Api Enpoint</param>
|
|
/// <param name="data">Data for send to API</param>
|
|
/// <exception cref="Exception">Error Message</exception>
|
|
public async void PostData<Type>(string Endpoint, Type data)
|
|
{
|
|
StringContent sc = new(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
|
|
|
|
HttpResponseMessage response = await _httpClient.PostAsync(new Uri(Endpoint), sc);
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
return;
|
|
}
|
|
else
|
|
{
|
|
throw new Exception(response.EnsureSuccessStatusCode().Content.ToString());
|
|
}
|
|
|
|
}
|
|
|
|
/// <summary>
|
|
/// Delete data from Api with DELETE method
|
|
/// </summary>
|
|
/// <param name="Endpoint">Api Endpoint</param>
|
|
/// <exception cref="Exception">Error message</exception>
|
|
public async void DeleteData(string Endpoint)
|
|
{
|
|
HttpResponseMessage response = await _httpClient.DeleteAsync(new Uri(Endpoint));
|
|
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
return;
|
|
}
|
|
else
|
|
{
|
|
throw new Exception(response.EnsureSuccessStatusCode().Content.ToString());
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
}
|
|
}
|