68 lines
2.2 KiB
C#
68 lines
2.2 KiB
C#
using Atomx.Common.Models;
|
|
using Atomx.Utils.Json;
|
|
using System.Net.Http.Json;
|
|
using System.Text;
|
|
|
|
namespace Atomx.Admin.Client.Services
|
|
{
|
|
public class HttpService(HttpClient httpClient)
|
|
{
|
|
public async Task<T> Get<T>(string url)
|
|
{
|
|
var response = await httpClient.GetAsync(url);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var content = await response.Content.ReadAsStringAsync();
|
|
return content.FromJson<T>();
|
|
}
|
|
else
|
|
{
|
|
throw new Exception($"Error: {response.StatusCode}");
|
|
}
|
|
}
|
|
|
|
public async Task<T> Post<T>(string url, object data)
|
|
{
|
|
var json = data.ToJson();
|
|
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
|
var response = await httpClient.PostAsync(url, content);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var responseContent = await response.Content.ReadAsStringAsync();
|
|
return responseContent.FromJson<T>();
|
|
}
|
|
else
|
|
{
|
|
throw new Exception($"Error: {response.StatusCode}");
|
|
}
|
|
}
|
|
|
|
public async Task<ApiResult<PagingList<T>>> GetPagingList<T>(string url, object data, int page, int size = 20)
|
|
{
|
|
try
|
|
{
|
|
if (page < 1)
|
|
{
|
|
page = 1;
|
|
}
|
|
url = $"{url}?page={page}&size={size}";
|
|
var response = await httpClient.PostAsJsonAsync(url, data);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var content = await response.Content.ReadAsStringAsync();
|
|
return content.FromJson<ApiResult<PagingList<T>>>();
|
|
}
|
|
else
|
|
{
|
|
throw new Exception($"Error: {response.StatusCode}");
|
|
}
|
|
}
|
|
catch (HttpRequestException ex)
|
|
{
|
|
Console.WriteLine(ex.ToString());
|
|
throw new Exception($"api {url} service failure");
|
|
}
|
|
}
|
|
}
|
|
}
|