|
@@ -0,0 +1,334 @@
|
|
|
+using DW5S.Repostory;
|
|
|
+using Newtonsoft.Json;
|
|
|
+using System;
|
|
|
+using System.Collections.Generic;
|
|
|
+using System.IO;
|
|
|
+using System.Linq;
|
|
|
+using System.Net.Http;
|
|
|
+using System.Security.Policy;
|
|
|
+using System.Text;
|
|
|
+using System.Threading;
|
|
|
+using System.Threading.Tasks;
|
|
|
+
|
|
|
+/// <summary>
|
|
|
+/// http调用帮助类
|
|
|
+/// </summary>
|
|
|
+public class HttpHelper
|
|
|
+{
|
|
|
+ /// <summary>
|
|
|
+ /// 文件删除模型
|
|
|
+ /// </summary>
|
|
|
+ class FileDeleteDto
|
|
|
+ {
|
|
|
+ /// <summary>
|
|
|
+ /// 要删除的服务器上的文件名称
|
|
|
+ /// </summary>
|
|
|
+ public List<string> Files { get; set; }
|
|
|
+ }
|
|
|
+ static HttpHelper()
|
|
|
+ {
|
|
|
+ //client = new HttpClient(new HttpClientHandler()
|
|
|
+ //{
|
|
|
+ // UseCookies = false,
|
|
|
+ // UseDefaultCredentials = false,
|
|
|
+ // UseProxy = false,
|
|
|
+ // AllowAutoRedirect = false,
|
|
|
+ //});
|
|
|
+ //client.Timeout = TimeSpan.FromSeconds(60);
|
|
|
+ ////client.MaxResponseContentBufferSize //该值默认为2GB
|
|
|
+
|
|
|
+ //downLoadClient = new HttpClient(new HttpClientHandler()
|
|
|
+ //{
|
|
|
+ // UseCookies = false,
|
|
|
+ // UseDefaultCredentials = false,
|
|
|
+ // UseProxy = false,
|
|
|
+ // AllowAutoRedirect = false,
|
|
|
+ //});
|
|
|
+ //downLoadClient.Timeout = TimeSpan.FromSeconds(180);
|
|
|
+ }
|
|
|
+ private static readonly string httpKey = "DW5S";
|
|
|
+ private static readonly string httpFileKey = "DW5S_File";
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ ///
|
|
|
+ /// </summary>
|
|
|
+ /// <typeparam name="T"></typeparam>
|
|
|
+ /// <param name="url"></param>
|
|
|
+ /// <param name="dto"></param>
|
|
|
+ /// <param name="token"></param>
|
|
|
+ /// <returns></returns>
|
|
|
+ public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto, CancellationToken token = default)
|
|
|
+ {
|
|
|
+ url = SysConfig.GetUrl(url);
|
|
|
+ var factory = IocContainer.GetService<IHttpClientFactory>();
|
|
|
+ var client = factory.CreateClient(httpKey);
|
|
|
+ var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
|
|
|
+ var message = new HttpRequestMessage(HttpMethod.Post, url);
|
|
|
+ message.Content = content;
|
|
|
+ var response = await client.SendAsync(message, token);
|
|
|
+ message.Dispose();//http1.1没啥用,http2有用
|
|
|
+ response.EnsureSuccessStatusCode();
|
|
|
+ var result = await response.Content.ReadAsStringAsync();
|
|
|
+ var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
|
|
|
+ return AjaxResult;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static async Task<AjaxResult> PostRequestAsync(string url, object dto, CancellationToken token = default)
|
|
|
+ {
|
|
|
+ url = SysConfig.GetUrl(url);
|
|
|
+ var factory = IocContainer.GetService<IHttpClientFactory>();
|
|
|
+ var client = factory.CreateClient(httpKey);
|
|
|
+
|
|
|
+ var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
|
|
|
+ var message = new HttpRequestMessage(HttpMethod.Post, url);
|
|
|
+ message.Content = content;
|
|
|
+ var response = await client.SendAsync(message, token);
|
|
|
+ message.Dispose();//http1.1没啥用,http2有用
|
|
|
+ response.EnsureSuccessStatusCode();
|
|
|
+ var result = await response.Content.ReadAsStringAsync();
|
|
|
+ var AjaxResult = JsonConvert.DeserializeObject<AjaxResult>(result);
|
|
|
+ return AjaxResult;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static async Task<AjaxResult<T>> GetRequestAsync<T>(string url)
|
|
|
+ {
|
|
|
+ url = SysConfig.GetUrl(url);
|
|
|
+ var factory = IocContainer.GetService<IHttpClientFactory>();
|
|
|
+ var client = factory.CreateClient(httpKey);
|
|
|
+
|
|
|
+ var response = await client.GetAsync(url);
|
|
|
+ response.EnsureSuccessStatusCode();
|
|
|
+ var result = await response.Content.ReadAsStringAsync();
|
|
|
+ var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
|
|
|
+ return AjaxResult;
|
|
|
+ }
|
|
|
+
|
|
|
+ public static async Task<bool> DownloadWithNameAsync(string remoteFileName, string localFile)
|
|
|
+ {
|
|
|
+ string url = SysConfig.GetUrl($"upload/{remoteFileName}");
|
|
|
+ var factory = IocContainer.GetService<IHttpClientFactory>();
|
|
|
+ var client = factory.CreateClient(httpFileKey);
|
|
|
+ var responseMessage = await client.GetAsync(url);
|
|
|
+ if (responseMessage.IsSuccessStatusCode)
|
|
|
+ {
|
|
|
+ using (var fs = File.Create(localFile))
|
|
|
+ {
|
|
|
+ // 获取结果,并转成 stream 保存到本地。
|
|
|
+ var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
|
|
|
+ streamFromService.CopyTo(fs);
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ else
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ public static async Task<bool> DownloadAsync(string url, string localFile)
|
|
|
+ {
|
|
|
+ var factory = IocContainer.GetService<IHttpClientFactory>();
|
|
|
+ var client = factory.CreateClient(httpFileKey);
|
|
|
+ var responseMessage = await client.GetAsync(url);
|
|
|
+ if (responseMessage.IsSuccessStatusCode)
|
|
|
+ {
|
|
|
+ using (var fs = File.Create(localFile))
|
|
|
+ {
|
|
|
+ // 获取结果,并转成 stream 保存到本地。
|
|
|
+ var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
|
|
|
+ streamFromService.CopyTo(fs);
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ else
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ private static string GetMimeType(string fileName)
|
|
|
+ {
|
|
|
+ string ext = Path.GetExtension(fileName).ToLower();
|
|
|
+ return ext switch
|
|
|
+ {
|
|
|
+ ".txt" => "text/plain",
|
|
|
+ ".jpg" or ".jpeg" => "image/jpeg",
|
|
|
+ ".png" => "image/png",
|
|
|
+ ".pdf" => "application/pdf",
|
|
|
+ _ => "application/octet-stream"
|
|
|
+ };
|
|
|
+ }
|
|
|
+
|
|
|
+ public static async Task<string> UploadFileAsync(string localFile, string baseUrl, CancellationToken token = default)
|
|
|
+ {
|
|
|
+ string url = SysConfig.GetUrl("File/UploadFileAsync");
|
|
|
+ try
|
|
|
+ {
|
|
|
+ var factory = IocContainer.GetService<IHttpClientFactory>();
|
|
|
+ var client = factory.CreateClient(httpFileKey);
|
|
|
+ using (var fileStream = File.OpenRead(localFile))
|
|
|
+ using (var fileContent = new StreamContent(fileStream))
|
|
|
+ {
|
|
|
+ // 3. (可选)设置文件 MIME 类型
|
|
|
+ string fileName = Path.GetFileName(localFile);
|
|
|
+ string contentType = GetMimeType(fileName);
|
|
|
+ fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
|
|
|
+
|
|
|
+ // 4. 构造 MultipartFormDataContent
|
|
|
+ using var formData = new MultipartFormDataContent();
|
|
|
+ formData.Add(fileContent, "file", fileName);
|
|
|
+ var response = await client.PostAsync(url, formData);
|
|
|
+ if (response.IsSuccessStatusCode)
|
|
|
+ {
|
|
|
+ string responseBody = await response.Content.ReadAsStringAsync();
|
|
|
+ var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<string>>(responseBody);
|
|
|
+ if (AjaxResult.code == 200)
|
|
|
+ {
|
|
|
+ return AjaxResult.data;
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ throw new Exception(AjaxResult.msg);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ throw new Exception($"上传文件{Path.GetFileName(localFile)}到{url}失败!");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ catch (TaskCanceledException)
|
|
|
+ {
|
|
|
+ if (token != default && token.IsCancellationRequested)
|
|
|
+ throw new TaskCanceledException();
|
|
|
+ else
|
|
|
+ throw new Exception($"上传文件{Path.GetFileName(localFile)}到{url}超时!");
|
|
|
+
|
|
|
+ }
|
|
|
+ catch (Exception ex)
|
|
|
+ {
|
|
|
+ throw new Exception($"上传文件{Path.GetFileName(localFile)}到{url}失败!", ex);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ ///// <summary>
|
|
|
+ ///// 上传文件,wav文件会自动去掉44字节头
|
|
|
+ ///// </summary>
|
|
|
+ ///// <param name="localFile"></param>
|
|
|
+ ///// <param name="baseUrl"></param>
|
|
|
+ ///// <param name="token"></param>
|
|
|
+ ///// <returns></returns>
|
|
|
+ //public static async Task<string> UploadFileAsync(string localFile, string baseUrl, CancellationToken token = default)
|
|
|
+ //{
|
|
|
+ // string uploadUrl = baseUrl;
|
|
|
+ // if (baseUrl.EndsWith("/"))
|
|
|
+ // uploadUrl += "File/UploadFileAsync";
|
|
|
+ // else
|
|
|
+ // uploadUrl += "/File/UploadFileAsync";
|
|
|
+ // try
|
|
|
+ // {
|
|
|
+ // // 添加文件内容到 MultipartFormDataContent
|
|
|
+ // FileInfo info = new FileInfo(localFile);
|
|
|
+ // bool isWav = info.Extension.ToLower() == ".wav";
|
|
|
+ // byte[] fileBytes = File.ReadAllBytes(localFile);
|
|
|
+ // if (isWav)
|
|
|
+ // {
|
|
|
+ // fileBytes = fileBytes.Skip(44).ToArray();//wav文件有44字节头
|
|
|
+ // }
|
|
|
+ // MultipartFormDataContent content = new MultipartFormDataContent();
|
|
|
+ // ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
|
|
|
+ // content.Add(fileContent, "file", Path.GetFileName(localFile));
|
|
|
+ // var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
|
|
|
+ // message.Content = content;
|
|
|
+ // var response = await downLoadClient.SendAsync(message, token);
|
|
|
+ // message.Dispose();
|
|
|
+ // response.EnsureSuccessStatusCode();
|
|
|
+ // var result = await response.Content.ReadAsStringAsync();
|
|
|
+ // var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<string>>(result);
|
|
|
+ // if (AjaxResult.code == 200)
|
|
|
+ // {
|
|
|
+ // return AjaxResult.data;
|
|
|
+ // }
|
|
|
+ // else
|
|
|
+ // {
|
|
|
+ // throw new Exception(AjaxResult.msg);
|
|
|
+ // }
|
|
|
+ // }
|
|
|
+ // catch (TaskCanceledException)
|
|
|
+ // {
|
|
|
+ // if (token != default && token.IsCancellationRequested)
|
|
|
+ // throw new TaskCanceledException();
|
|
|
+ // else
|
|
|
+ // throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}超时!");
|
|
|
+
|
|
|
+ // }
|
|
|
+ // catch (Exception ex)
|
|
|
+ // {
|
|
|
+ // throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!", ex);
|
|
|
+ // }
|
|
|
+ //}
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 删除文件
|
|
|
+ /// </summary>
|
|
|
+ /// <param name="files">要删除的文件</param>
|
|
|
+ /// <param name="baseUrl">baseUrl</param>
|
|
|
+ /// <returns></returns>
|
|
|
+ public static async Task<int> DeleteFileAsync(params string[] files)
|
|
|
+ {
|
|
|
+ string url = SysConfig.GetUrl("File/DeleteFiles");
|
|
|
+ var factory = IocContainer.GetService<IHttpClientFactory>();
|
|
|
+ var client = factory.CreateClient(httpKey);
|
|
|
+ FileDeleteDto dto = new FileDeleteDto()
|
|
|
+ {
|
|
|
+ Files = files.ToList()
|
|
|
+ };
|
|
|
+ var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
|
|
|
+ var message = new HttpRequestMessage(HttpMethod.Post, url);
|
|
|
+ message.Content = content;
|
|
|
+ var response = await client.SendAsync(message);
|
|
|
+ message.Dispose();
|
|
|
+ response.EnsureSuccessStatusCode();
|
|
|
+ var result = await response.Content.ReadAsStringAsync();
|
|
|
+ var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<int>>(result);
|
|
|
+ return AjaxResult.data;
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+/// <summary>
|
|
|
+/// Http接口返回泛型对象
|
|
|
+/// </summary>
|
|
|
+public class AjaxResult<T>
|
|
|
+{
|
|
|
+ /// <summary>
|
|
|
+ /// 返回对象
|
|
|
+ /// </summary>
|
|
|
+ public T data { get; set; }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 返回消息
|
|
|
+ /// </summary>
|
|
|
+ public string msg { get; set; } = "ok";
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 状态码.成功=200,失败=0
|
|
|
+ /// </summary>
|
|
|
+ public int code { get; set; } = 200;
|
|
|
+
|
|
|
+}
|
|
|
+/// <summary>
|
|
|
+/// Http接口返回对象
|
|
|
+/// </summary>
|
|
|
+public class AjaxResult
|
|
|
+{
|
|
|
+ /// <summary>
|
|
|
+ /// 返回对象
|
|
|
+ /// </summary>
|
|
|
+ public object data { get; set; }
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 返回消息
|
|
|
+ /// </summary>
|
|
|
+ public string msg { get; set; } = "ok";
|
|
|
+
|
|
|
+ /// <summary>
|
|
|
+ /// 状态码.成功=200,失败=0
|
|
|
+ /// </summary>
|
|
|
+ public int code { get; set; } = 200;
|
|
|
+
|
|
|
+}
|
|
|
+
|