pcut_uwp/PCUT/PCUT.API/ApiClient.cs

81 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Text;
namespace PCUT.API
{
public static class ApiClient<T>
{
private static HttpClient httpClient { get;set; }
private static string baseApiUrl { get; set; }
public static void Initial(string baseURL)
{
if (httpClient != null) return;
httpClient = new HttpClient();
baseApiUrl = baseURL;
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static void SetAuthToken(string token)
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
public static async Task<List<T>> GetAllAsync(string path)
{
HttpResponseMessage response = await httpClient.GetAsync($"{baseApiUrl}/{path}");
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<T>>(content);
}
public static async Task<T> GetByIdAsync(string path, int id)
{
HttpResponseMessage response = await httpClient.GetAsync($"{baseApiUrl}/{path}/{id}");
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(content);
}
public static async Task<T> CreateAsync(string path, T entity)
{
string json = JsonConvert.SerializeObject(entity);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync($"{baseApiUrl}/{path}", content);
response.EnsureSuccessStatusCode();
string responseContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(responseContent);
}
public static async Task<T> UpdateAsync(string path, int id, T entity)
{
string json = JsonConvert.SerializeObject(entity);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PutAsync($"{baseApiUrl}/{path}/{id}", content);
response.EnsureSuccessStatusCode();
string responseContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(responseContent);
}
public static async Task<bool> DeleteAsync(string path, int id)
{
HttpResponseMessage response = await httpClient.DeleteAsync($"{baseApiUrl}/{path}/{id}");
response.EnsureSuccessStatusCode();
return response.IsSuccessStatusCode;
}
}
}