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 { 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> GetAllAsync(string path) { HttpResponseMessage response = await httpClient.GetAsync($"{baseApiUrl}/{path}"); response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject>(content); } public static async Task GetByIdAsync(string path, int id) { HttpResponseMessage response = await httpClient.GetAsync($"{baseApiUrl}/{path}/{id}"); response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject(content); } public static async Task 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(responseContent); } public static async Task 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(responseContent); } public static async Task DeleteAsync(string path, int id) { HttpResponseMessage response = await httpClient.DeleteAsync($"{baseApiUrl}/{path}/{id}"); response.EnsureSuccessStatusCode(); return response.IsSuccessStatusCode; } } }