123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334 |
- 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;
- }
|