HttpHelper.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Security.Policy;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. /// <summary>
  12. /// http调用帮助类
  13. /// </summary>
  14. public class HttpHelper
  15. {
  16. /// <summary>
  17. /// 文件删除模型
  18. /// </summary>
  19. class FileDeleteDto
  20. {
  21. /// <summary>
  22. /// 要删除的服务器上的文件名称
  23. /// </summary>
  24. public List<string> Files { get; set; }
  25. }
  26. static HttpHelper()
  27. {
  28. client = new HttpClient(new HttpClientHandler()
  29. {
  30. UseCookies = false,
  31. UseDefaultCredentials = false,
  32. UseProxy = false,
  33. AllowAutoRedirect = false,
  34. });
  35. client.Timeout = TimeSpan.FromSeconds(60);
  36. //client.MaxResponseContentBufferSize //该值默认为2GB
  37. downLoadClient = new HttpClient(new HttpClientHandler()
  38. {
  39. UseCookies = false,
  40. UseDefaultCredentials = false,
  41. UseProxy = false,
  42. AllowAutoRedirect = false,
  43. });
  44. downLoadClient.Timeout = TimeSpan.FromSeconds(180);
  45. }
  46. private static HttpClient client;
  47. private static HttpClient downLoadClient;
  48. public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto, CancellationToken token = default)
  49. {
  50. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  51. var message = new HttpRequestMessage(HttpMethod.Post, url);
  52. message.Content = content;
  53. var response = await client.SendAsync(message, token);
  54. message.Dispose();//http1.1没啥用,http2有用
  55. response.EnsureSuccessStatusCode();
  56. var result = await response.Content.ReadAsStringAsync();
  57. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  58. return AjaxResult;
  59. }
  60. public static async Task<AjaxResult> PostRequestAsync(string url, object dto, CancellationToken token = default)
  61. {
  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>(result);
  70. return AjaxResult;
  71. }
  72. public static async Task<AjaxResult<T>> GetRequestAsync<T>(string url)
  73. {
  74. var response = await client.GetAsync(url);
  75. response.EnsureSuccessStatusCode();
  76. var result = await response.Content.ReadAsStringAsync();
  77. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  78. return AjaxResult;
  79. }
  80. public static async Task<bool> DownloadFileAsync(string baseUrl, string remoteFileName, string localFile)
  81. {
  82. baseUrl = baseUrl.Replace("/api", "");
  83. if (!baseUrl.EndsWith("/"))
  84. baseUrl += "/";
  85. var server = new Uri(baseUrl + $"wwwroot/{remoteFileName}");
  86. var responseMessage = await downLoadClient.GetAsync(server);
  87. if (responseMessage.IsSuccessStatusCode)
  88. {
  89. using (var fs = File.Create(localFile))
  90. {
  91. // 获取结果,并转成 stream 保存到本地。
  92. var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
  93. streamFromService.CopyTo(fs);
  94. }
  95. return true;
  96. }
  97. else
  98. return false;
  99. }
  100. public static async Task<bool> DownloadFileAsync(string url, string localFile)
  101. {
  102. var server = new Uri(url);
  103. var responseMessage = await downLoadClient.GetAsync(server);
  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. /// <summary>
  118. /// 上传文件,wav文件会自动去掉44字节头
  119. /// </summary>
  120. /// <param name="localFile"></param>
  121. /// <param name="baseUrl"></param>
  122. /// <param name="token"></param>
  123. /// <returns></returns>
  124. public static async Task<string> UploadFileAsync(string localFile, string baseUrl, CancellationToken token = default)
  125. {
  126. string uploadUrl = baseUrl;
  127. if (baseUrl.EndsWith("/"))
  128. uploadUrl += "File/UploadFileAsync";
  129. else
  130. uploadUrl += "/File/UploadFileAsync";
  131. try
  132. {
  133. // 添加文件内容到 MultipartFormDataContent
  134. FileInfo info = new FileInfo(localFile);
  135. bool isWav = info.Extension.ToLower() == ".wav";
  136. byte[] fileBytes = File.ReadAllBytes(localFile);
  137. if (isWav)
  138. {
  139. fileBytes = fileBytes.Skip(44).ToArray();//wav文件有44字节头
  140. }
  141. MultipartFormDataContent content = new MultipartFormDataContent();
  142. ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
  143. content.Add(fileContent, "file", Path.GetFileName(localFile));
  144. var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
  145. message.Content = content;
  146. var response = await downLoadClient.SendAsync(message, token);
  147. message.Dispose();
  148. response.EnsureSuccessStatusCode();
  149. var result = await response.Content.ReadAsStringAsync();
  150. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<string>>(result);
  151. if (AjaxResult.code == 200)
  152. {
  153. return AjaxResult.data;
  154. }
  155. else
  156. {
  157. throw new Exception(AjaxResult.msg);
  158. }
  159. }
  160. catch (TaskCanceledException)
  161. {
  162. if (token != default && token.IsCancellationRequested)
  163. throw new TaskCanceledException();
  164. else
  165. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}超时!");
  166. }
  167. catch (Exception ex)
  168. {
  169. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!", ex);
  170. }
  171. }
  172. /// <summary>
  173. /// 删除文件
  174. /// </summary>
  175. /// <param name="files">要删除的文件</param>
  176. /// <param name="baseUrl">baseUrl</param>
  177. /// <returns></returns>
  178. public static async Task<int> DeleteFileAsync(string baseUrl, params string[] files)
  179. {
  180. FileDeleteDto dto = new FileDeleteDto()
  181. {
  182. Files = files.ToList()
  183. };
  184. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  185. var message = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/File/DeleteFiles");
  186. message.Content = content;
  187. var response = await client.SendAsync(message);
  188. message.Dispose();
  189. response.EnsureSuccessStatusCode();
  190. var result = await response.Content.ReadAsStringAsync();
  191. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<int>>(result);
  192. return AjaxResult.data;
  193. }
  194. }
  195. /// <summary>
  196. /// Http接口返回泛型对象
  197. /// </summary>
  198. public class AjaxResult<T>
  199. {
  200. /// <summary>
  201. /// 返回对象
  202. /// </summary>
  203. public T data { get; set; }
  204. /// <summary>
  205. /// 返回消息
  206. /// </summary>
  207. public string msg { get; set; } = "ok";
  208. /// <summary>
  209. /// 状态码.成功=200,失败=0
  210. /// </summary>
  211. public int code { get; set; } = 200;
  212. }
  213. /// <summary>
  214. /// Http接口返回对象
  215. /// </summary>
  216. public class AjaxResult
  217. {
  218. /// <summary>
  219. /// 返回对象
  220. /// </summary>
  221. public object data { get; set; }
  222. /// <summary>
  223. /// 返回消息
  224. /// </summary>
  225. public string msg { get; set; } = "ok";
  226. /// <summary>
  227. /// 状态码.成功=200,失败=0
  228. /// </summary>
  229. public int code { get; set; } = 200;
  230. }