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<IHttpClientFactory>();
|
}
|
|
public static HttpClient GetClient()
|
{
|
return ClientFactory.CreateClient(BASE_CLIENT_NAME);
|
}
|
|
public static HttpClient GetClient(string clientName)
|
{
|
return ClientFactory.CreateClient(clientName);
|
}
|
|
|
public static Result<T> GetSyncAction<T>(this HttpClient client, string url, params object[] models)
|
{
|
return JsonUtil.Deserialize<Result<T>>(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<string> task = client.GetStringAsync(url);
|
task.Wait();
|
return task.Result;
|
|
}
|
public static async Task<T> GetAsyncAction<T>(this HttpClient client, string url, params object[] models)
|
{
|
foreach (object model in models)
|
{
|
url = url.ModelToUriParam(model);
|
}
|
return JsonUtil.Deserialize<T>(await client.GetStringAsync(url));
|
}
|
|
public static T PostSyncAction<T>(this HttpClient client, string url, string data)
|
{
|
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
|
Task<HttpResponseMessage> task = client.PostAsync(url, content);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
response.EnsureSuccessStatusCode();
|
Task<string> task2 = response.Content.ReadAsStringAsync();
|
task2.Wait();
|
string responseBody = task2.Result;
|
return JsonUtil.Deserialize<T>(responseBody);
|
}
|
|
public static Result<T> PostSyncAction<T>(this HttpClient client, object data, string url)
|
{
|
string dataStr = JsonUtil.Serialize(data);
|
StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
|
Task<HttpResponseMessage> task = client.PostAsync(url, content);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
response.EnsureSuccessStatusCode();
|
Task<string> task2 = response.Content.ReadAsStringAsync();
|
task2.Wait();
|
string responseBody = task2.Result;
|
return JsonUtil.Deserialize<Result<T>>(responseBody);
|
}
|
|
public static string PostSyncAction(this HttpClient client, string url, string data)
|
{
|
StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
|
Task<HttpResponseMessage> task = client.PostAsync(url, content);
|
task.Wait();
|
HttpResponseMessage response = task.Result;
|
response.EnsureSuccessStatusCode();
|
Task<string> task2 = response.Content.ReadAsStringAsync();
|
task2.Wait();
|
return task2.Result;
|
}
|
|
public static async Task<T> PostAsyncAction<T>(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<T>(await response.Content.ReadAsStringAsync());
|
}
|
|
public static async Task<T> PostAsyncAction<T>(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<T>(await response.Content.ReadAsStringAsync());
|
}
|
|
public static async Task<string> 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<string, string>)
|
{
|
Dictionary<string, string> dict = (Dictionary<string, string>)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();
|
}
|
}
|
}
|