using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Reflection; using System.Web; using System.IO; using log4net.Plugin; using PdmSwPlugin.Common.Setting; namespace AutoUpdater.Util { public static class HttpUtil { private static readonly string ApiKey = "X-Access-Token"; public static readonly string BASE_CLIENT_NAME = "BaseClient"; private static IHttpClientFactory ClientFactory; [Obsolete] private static string DownloadDir; public static void Init() { ServiceProvider ser = new ServiceCollection().AddHttpClient(BASE_CLIENT_NAME, c => { c.BaseAddress = new Uri(PluginSetting.Instance.BaseAddress); c.Timeout = TimeSpan.FromSeconds(PluginSetting.Instance.TimeOut); c.DefaultRequestHeaders .Add(ApiKey, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2Nzg5NjI5NzgsInVzZXJuYW1lIjoiY2hlbmhhb3JhbiJ9.Ir8u0j5mRsmi-QGtAsYP-cZxlRjnYBDf7sNoHf3uWQs"); }) .Services .BuildServiceProvider(); ClientFactory = ser.GetService(); } public static HttpClient GetClient() { return ClientFactory.CreateClient(BASE_CLIENT_NAME); } public static HttpClient GetClient(string clientName) { return ClientFactory.CreateClient(clientName); } public static Result GetSyncAction(this HttpClient client, string url, params object[] models) { return JsonUtil.Deserialize>(GetSyncAction(client, url, models)); } public static string GetSyncAction(this HttpClient client, string url, params object[] models) { foreach (object model in models) { url = url.ModelToUriParam(model); } Task task = client.GetStringAsync(url); task.Wait(); return task.Result; } public static async Task GetAsyncAction(this HttpClient client, string url, params object[] models) { foreach (object model in models) { url = url.ModelToUriParam(model); } return JsonUtil.Deserialize(await client.GetStringAsync(url)); } public static T PostSyncAction(this HttpClient client, string url, string data) { StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); Task task = client.PostAsync(url, content); task.Wait(); HttpResponseMessage response = task.Result; response.EnsureSuccessStatusCode(); Task task2 = response.Content.ReadAsStringAsync(); task2.Wait(); string responseBody = task2.Result; return JsonUtil.Deserialize(responseBody); } public static Result PostSyncAction(this HttpClient client, object data, string url) { string dataStr = JsonUtil.Serialize(data); StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json"); Task task = client.PostAsync(url, content); task.Wait(); HttpResponseMessage response = task.Result; response.EnsureSuccessStatusCode(); Task task2 = response.Content.ReadAsStringAsync(); task2.Wait(); string responseBody = task2.Result; return JsonUtil.Deserialize>(responseBody); } public static string PostSyncAction(this HttpClient client, string url, string data) { StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); Task task = client.PostAsync(url, content); task.Wait(); HttpResponseMessage response = task.Result; response.EnsureSuccessStatusCode(); Task task2 = response.Content.ReadAsStringAsync(); task2.Wait(); return task2.Result; } public static async Task PostAsyncAction(this HttpClient client, string url, string data) { StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(url, content); _ = response.EnsureSuccessStatusCode(); return JsonUtil.Deserialize(await response.Content.ReadAsStringAsync()); } public static async Task PostAsyncAction(this HttpClient client, string url, object data) { string dataStr = JsonUtil.Serialize(data); StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(url, content); _ = response.EnsureSuccessStatusCode(); return JsonUtil.Deserialize(await response.Content.ReadAsStringAsync()); } public static async Task GetDownload(this HttpClient client, string url, string dir, string fileName, params object[] models) { foreach (object model in models) { url = url.ModelToUriParam(model); } HttpResponseMessage response = await client.GetAsync(url); // 服务器返回的文件名 string originFileName = HttpUtility.UrlDecode(response.Headers.GetValues("FileName").FirstOrDefault()); string fullPath; using (Stream stream = await response.Content.ReadAsStreamAsync()) { // 拼接一个新的本地文件名 string suffix = Path.GetExtension(originFileName); string newFileName = Path.GetFileNameWithoutExtension(fileName) + suffix; fullPath = $"{dir}/{newFileName}"; using (FileStream fs = new FileStream(fullPath, FileMode.Create)) { byte[] buffer = new byte[1024]; int readLength = 0; int length; while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0) { readLength += length; fs.Write(buffer, 0, length); } } } return fullPath; } public static async void GetDownloadWithName(this HttpClient client, string url, params object[] models) { foreach (object model in models) { url = url.ModelToUriParam(model); } string dir = DownloadDir; HttpResponseMessage response = await client.GetAsync(url); string fileName = HttpUtility.UrlDecode(response.Headers.GetValues("FileName").FirstOrDefault()); using (Stream stream = await response.Content.ReadAsStreamAsync()) { // string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString()); string suffix = Path.GetExtension(fileName); using (FileStream fs = new FileStream($"{dir}/{fileName}", FileMode.CreateNew)) { byte[] buffer = new byte[1024]; int readLength = 0; int length; while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0) { readLength += length; fs.Write(buffer, 0, length); } } } } public static string ModelToUriParam(this string url, object obj) { PropertyInfo[] properties = obj.GetType().GetProperties(); StringBuilder sb = new StringBuilder() .Append(url).Append("?"); if (obj is Dictionary) { Dictionary dict = (Dictionary)obj; foreach (var item in dict) { if (item.Value == null || string.IsNullOrWhiteSpace(item.Value)) { continue; } sb = sb.Append(item.Key) .Append("=") .Append(HttpUtility.UrlEncode(item.Value)) .Append("&"); } } else { foreach (PropertyInfo p in properties) { object v = p.GetValue(obj, null); if (v == null || string.IsNullOrWhiteSpace(v.ToString())) { continue; } sb = sb.Append(p.Name) .Append("=") .Append(HttpUtility.UrlEncode(v.ToString())) .Append("&"); } } sb = sb.Remove(sb.Length - 1, 1); return sb.ToString(); } } }