MasstransferExporter/MasstransferInfrastructure/Http/ApiClient.cs

75 lines
2.2 KiB
C#

using System.Net.Http.Json;
namespace MasstransferCommon.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");
}
/// <summary>
/// 异步Get请求
/// </summary>
/// <param name="url"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static async Task<T?> GetAsync<T>(string url)
{
using var response = await Client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<T>();
}
/// <summary>
/// 异步 Post请求
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static async Task<T?> PostAsync<T>(string url, object? data)
{
using var response = await Client.PostAsJsonAsync(url, data);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<T>();
}
/// <summary>
/// 异步 Put请求
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static async Task<T?> PutAsync<T>(string url, object? data)
{
using var response = await Client.PutAsJsonAsync(url, data);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<T>();
}
/// <summary>
/// 异步 Delete请求
/// </summary>
/// <param name="url"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static async Task<T?> DeleteAsync<T>(string url)
{
using var response = await Client.DeleteAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<T>();
}
public void Dispose()
{
Client.Dispose();
}
}