36 lines
1.1 KiB
C#
36 lines
1.1 KiB
C#
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Net.Http;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Chtn.CSharp.SDK.Core
|
|
{
|
|
public class ApiClient
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
private readonly string _baseUrl;
|
|
|
|
public ApiClient(string baseUrl)
|
|
{
|
|
_baseUrl = baseUrl.EndsWith("/") ? baseUrl : baseUrl + "/";
|
|
_httpClient = new HttpClient();
|
|
}
|
|
|
|
public async Task<TResponse> PostAsync<TRequest, TResponse>(string endpoint, TRequest data)
|
|
{
|
|
var json = JsonConvert.SerializeObject(data);
|
|
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
|
|
|
var response = await _httpClient.PostAsync(_baseUrl + endpoint, content);
|
|
var responseJson = await response.Content.ReadAsStringAsync();
|
|
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
throw new Exception($"API Hiba ({response.StatusCode}): {responseJson}");
|
|
}
|
|
|
|
return JsonConvert.DeserializeObject<TResponse>(responseJson);
|
|
}
|
|
}
|
|
} |