using System.Net.Http.Json;
namespace DispenserCommon.Utils;
public class ApiClient : IDisposable
{
private static readonly HttpClient Client;
static ApiClient()
{
Client = new HttpClient();
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Add("Accept", "application/json");
Client.DefaultRequestHeaders.Add("Content-Type", "application/json");
}
///
/// 异步Get请求
///
///
///
///
public static async Task GetAsync(string url)
{
using var response = await Client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync();
}
///
/// 异步 Post请求
///
///
///
///
///
public static async Task PostAsync(string url, object? data)
{
using var response = await Client.PostAsJsonAsync(url, data);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync();
}
///
/// 异步 Put请求
///
///
///
///
///
public static async Task PutAsync(string url, object? data)
{
using var response = await Client.PutAsJsonAsync(url, data);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync();
}
///
/// 异步 Delete请求
///
///
///
///
public static async Task DeleteAsync(string url)
{
using var response = await Client.DeleteAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync();
}
public void Dispose()
{
Client.Dispose();
}
}