添加项目文件。
This commit is contained in:
67
Atomx.Admin/Atomx.Admin.Client/Services/HttpService.cs
Normal file
67
Atomx.Admin/Atomx.Admin.Client/Services/HttpService.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user