89 lines
2.7 KiB
C#
89 lines
2.7 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>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 异步请求下载文件
|
|
/// </summary>
|
|
/// <param name="fileUrl"></param>
|
|
/// <param name="destinationFilePath"></param>
|
|
public static async Task DownloadFileAsync(string fileUrl, string destinationFilePath)
|
|
{
|
|
using var response = await Client.GetAsync(fileUrl);
|
|
response.EnsureSuccessStatusCode();
|
|
|
|
using var fileStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
|
|
await response.Content.CopyToAsync(fileStream);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Client.Dispose();
|
|
}
|
|
} |