HttpHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. using DW5S.Repostory;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Security.Policy;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. /// <summary>
  13. /// http调用帮助类
  14. /// </summary>
  15. public class HttpHelper
  16. {
  17. /// <summary>
  18. /// 文件删除模型
  19. /// </summary>
  20. class FileDeleteDto
  21. {
  22. /// <summary>
  23. /// 要删除的服务器上的文件名称
  24. /// </summary>
  25. public List<string> Files { get; set; }
  26. }
  27. static HttpHelper()
  28. {
  29. //client = new HttpClient(new HttpClientHandler()
  30. //{
  31. // UseCookies = false,
  32. // UseDefaultCredentials = false,
  33. // UseProxy = false,
  34. // AllowAutoRedirect = false,
  35. //});
  36. //client.Timeout = TimeSpan.FromSeconds(60);
  37. ////client.MaxResponseContentBufferSize //该值默认为2GB
  38. //downLoadClient = new HttpClient(new HttpClientHandler()
  39. //{
  40. // UseCookies = false,
  41. // UseDefaultCredentials = false,
  42. // UseProxy = false,
  43. // AllowAutoRedirect = false,
  44. //});
  45. //downLoadClient.Timeout = TimeSpan.FromSeconds(180);
  46. }
  47. private static readonly string httpKey = "DW5S";
  48. private static readonly string httpFileKey = "DW5S_File";
  49. /// <summary>
  50. ///
  51. /// </summary>
  52. /// <typeparam name="T"></typeparam>
  53. /// <param name="url"></param>
  54. /// <param name="dto"></param>
  55. /// <param name="token"></param>
  56. /// <returns></returns>
  57. public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto, CancellationToken token = default)
  58. {
  59. url = SysConfig.GetUrl(url);
  60. var factory = IocContainer.GetService<IHttpClientFactory>();
  61. var client = factory.CreateClient(httpKey);
  62. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  63. var message = new HttpRequestMessage(HttpMethod.Post, url);
  64. message.Content = content;
  65. var response = await client.SendAsync(message, token);
  66. message.Dispose();//http1.1没啥用,http2有用
  67. response.EnsureSuccessStatusCode();
  68. var result = await response.Content.ReadAsStringAsync();
  69. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  70. return AjaxResult;
  71. }
  72. public static async Task<AjaxResult> PostRequestAsync(string url, object dto, CancellationToken token = default)
  73. {
  74. url = SysConfig.GetUrl(url);
  75. var factory = IocContainer.GetService<IHttpClientFactory>();
  76. var client = factory.CreateClient(httpKey);
  77. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  78. var message = new HttpRequestMessage(HttpMethod.Post, url);
  79. message.Content = content;
  80. var response = await client.SendAsync(message, token);
  81. message.Dispose();//http1.1没啥用,http2有用
  82. response.EnsureSuccessStatusCode();
  83. var result = await response.Content.ReadAsStringAsync();
  84. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult>(result);
  85. return AjaxResult;
  86. }
  87. public static async Task<AjaxResult<T>> GetRequestAsync<T>(string url)
  88. {
  89. url = SysConfig.GetUrl(url);
  90. var factory = IocContainer.GetService<IHttpClientFactory>();
  91. var client = factory.CreateClient(httpKey);
  92. var response = await client.GetAsync(url);
  93. response.EnsureSuccessStatusCode();
  94. var result = await response.Content.ReadAsStringAsync();
  95. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  96. return AjaxResult;
  97. }
  98. public static async Task<bool> DownloadWithNameAsync(string remoteFileName, string localFile)
  99. {
  100. string url = SysConfig.GetUrl($"upload/{remoteFileName}");
  101. var factory = IocContainer.GetService<IHttpClientFactory>();
  102. var client = factory.CreateClient(httpFileKey);
  103. var responseMessage = await client.GetAsync(url);
  104. if (responseMessage.IsSuccessStatusCode)
  105. {
  106. using (var fs = File.Create(localFile))
  107. {
  108. // 获取结果,并转成 stream 保存到本地。
  109. var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
  110. streamFromService.CopyTo(fs);
  111. }
  112. return true;
  113. }
  114. else
  115. return false;
  116. }
  117. public static async Task<bool> DownloadAsync(string url, string localFile)
  118. {
  119. var factory = IocContainer.GetService<IHttpClientFactory>();
  120. var client = factory.CreateClient(httpFileKey);
  121. var responseMessage = await client.GetAsync(url);
  122. if (responseMessage.IsSuccessStatusCode)
  123. {
  124. using (var fs = File.Create(localFile))
  125. {
  126. // 获取结果,并转成 stream 保存到本地。
  127. var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
  128. streamFromService.CopyTo(fs);
  129. }
  130. return true;
  131. }
  132. else
  133. return false;
  134. }
  135. private static string GetMimeType(string fileName)
  136. {
  137. string ext = Path.GetExtension(fileName).ToLower();
  138. return ext switch
  139. {
  140. ".txt" => "text/plain",
  141. ".jpg" or ".jpeg" => "image/jpeg",
  142. ".png" => "image/png",
  143. ".pdf" => "application/pdf",
  144. _ => "application/octet-stream"
  145. };
  146. }
  147. public static async Task<string> UploadFileAsync(string localFile, string baseUrl, CancellationToken token = default)
  148. {
  149. string url = SysConfig.GetUrl("File/UploadFileAsync");
  150. try
  151. {
  152. var factory = IocContainer.GetService<IHttpClientFactory>();
  153. var client = factory.CreateClient(httpFileKey);
  154. using (var fileStream = File.OpenRead(localFile))
  155. using (var fileContent = new StreamContent(fileStream))
  156. {
  157. // 3. (可选)设置文件 MIME 类型
  158. string fileName = Path.GetFileName(localFile);
  159. string contentType = GetMimeType(fileName);
  160. fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
  161. // 4. 构造 MultipartFormDataContent
  162. using var formData = new MultipartFormDataContent();
  163. formData.Add(fileContent, "file", fileName);
  164. var response = await client.PostAsync(url, formData);
  165. if (response.IsSuccessStatusCode)
  166. {
  167. string responseBody = await response.Content.ReadAsStringAsync();
  168. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<string>>(responseBody);
  169. if (AjaxResult.code == 200)
  170. {
  171. return AjaxResult.data;
  172. }
  173. else
  174. {
  175. throw new Exception(AjaxResult.msg);
  176. }
  177. }
  178. else
  179. {
  180. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{url}失败!");
  181. }
  182. }
  183. }
  184. catch (TaskCanceledException)
  185. {
  186. if (token != default && token.IsCancellationRequested)
  187. throw new TaskCanceledException();
  188. else
  189. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{url}超时!");
  190. }
  191. catch (Exception ex)
  192. {
  193. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{url}失败!", ex);
  194. }
  195. }
  196. ///// <summary>
  197. ///// 上传文件,wav文件会自动去掉44字节头
  198. ///// </summary>
  199. ///// <param name="localFile"></param>
  200. ///// <param name="baseUrl"></param>
  201. ///// <param name="token"></param>
  202. ///// <returns></returns>
  203. //public static async Task<string> UploadFileAsync(string localFile, string baseUrl, CancellationToken token = default)
  204. //{
  205. // string uploadUrl = baseUrl;
  206. // if (baseUrl.EndsWith("/"))
  207. // uploadUrl += "File/UploadFileAsync";
  208. // else
  209. // uploadUrl += "/File/UploadFileAsync";
  210. // try
  211. // {
  212. // // 添加文件内容到 MultipartFormDataContent
  213. // FileInfo info = new FileInfo(localFile);
  214. // bool isWav = info.Extension.ToLower() == ".wav";
  215. // byte[] fileBytes = File.ReadAllBytes(localFile);
  216. // if (isWav)
  217. // {
  218. // fileBytes = fileBytes.Skip(44).ToArray();//wav文件有44字节头
  219. // }
  220. // MultipartFormDataContent content = new MultipartFormDataContent();
  221. // ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
  222. // content.Add(fileContent, "file", Path.GetFileName(localFile));
  223. // var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
  224. // message.Content = content;
  225. // var response = await downLoadClient.SendAsync(message, token);
  226. // message.Dispose();
  227. // response.EnsureSuccessStatusCode();
  228. // var result = await response.Content.ReadAsStringAsync();
  229. // var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<string>>(result);
  230. // if (AjaxResult.code == 200)
  231. // {
  232. // return AjaxResult.data;
  233. // }
  234. // else
  235. // {
  236. // throw new Exception(AjaxResult.msg);
  237. // }
  238. // }
  239. // catch (TaskCanceledException)
  240. // {
  241. // if (token != default && token.IsCancellationRequested)
  242. // throw new TaskCanceledException();
  243. // else
  244. // throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}超时!");
  245. // }
  246. // catch (Exception ex)
  247. // {
  248. // throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!", ex);
  249. // }
  250. //}
  251. /// <summary>
  252. /// 删除文件
  253. /// </summary>
  254. /// <param name="files">要删除的文件</param>
  255. /// <param name="baseUrl">baseUrl</param>
  256. /// <returns></returns>
  257. public static async Task<int> DeleteFileAsync(params string[] files)
  258. {
  259. string url = SysConfig.GetUrl("File/DeleteFiles");
  260. var factory = IocContainer.GetService<IHttpClientFactory>();
  261. var client = factory.CreateClient(httpKey);
  262. FileDeleteDto dto = new FileDeleteDto()
  263. {
  264. Files = files.ToList()
  265. };
  266. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  267. var message = new HttpRequestMessage(HttpMethod.Post, url);
  268. message.Content = content;
  269. var response = await client.SendAsync(message);
  270. message.Dispose();
  271. response.EnsureSuccessStatusCode();
  272. var result = await response.Content.ReadAsStringAsync();
  273. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<int>>(result);
  274. return AjaxResult.data;
  275. }
  276. }
  277. /// <summary>
  278. /// Http接口返回泛型对象
  279. /// </summary>
  280. public class AjaxResult<T>
  281. {
  282. /// <summary>
  283. /// 返回对象
  284. /// </summary>
  285. public T data { get; set; }
  286. /// <summary>
  287. /// 返回消息
  288. /// </summary>
  289. public string msg { get; set; } = "ok";
  290. /// <summary>
  291. /// 状态码.成功=200,失败=0
  292. /// </summary>
  293. public int code { get; set; } = 200;
  294. }
  295. /// <summary>
  296. /// Http接口返回对象
  297. /// </summary>
  298. public class AjaxResult
  299. {
  300. /// <summary>
  301. /// 返回对象
  302. /// </summary>
  303. public object data { get; set; }
  304. /// <summary>
  305. /// 返回消息
  306. /// </summary>
  307. public string msg { get; set; } = "ok";
  308. /// <summary>
  309. /// 状态码.成功=200,失败=0
  310. /// </summary>
  311. public int code { get; set; } = 200;
  312. }