HttpHelper.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. /// <summary>
  27. ///
  28. /// </summary>
  29. /// <typeparam name="T"></typeparam>
  30. /// <param name="url"></param>
  31. /// <param name="dto"></param>
  32. /// <param name="timeoutSeconds"></param>
  33. /// <param name="token"></param>
  34. /// <returns></returns>
  35. public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto, int timeoutSeconds = 60, CancellationToken token = default)
  36. {
  37. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  38. var handler = new HttpClientHandler() { UseCookies = false };
  39. HttpClient client = new HttpClient(handler);
  40. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  41. var message = new HttpRequestMessage(HttpMethod.Post, url);
  42. message.Content = content;
  43. var response = await client.SendAsync(message, token);
  44. response.EnsureSuccessStatusCode();
  45. var result = await response.Content.ReadAsStringAsync();
  46. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  47. return AjaxResult;
  48. }
  49. /// <summary>
  50. ///
  51. /// </summary>
  52. /// <param name="url"></param>
  53. /// <param name="dto"></param>
  54. /// <param name="token"></param>
  55. /// <param name="timeoutSeconds"></param>
  56. /// <returns></returns>
  57. public static async Task<AjaxResult> PostRequestAsync(string url, object dto, int timeoutSeconds = 60, CancellationToken token = default)
  58. {
  59. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  60. var handler = new HttpClientHandler() { UseCookies = false };
  61. HttpClient client = new HttpClient(handler);
  62. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  63. var message = new HttpRequestMessage(HttpMethod.Post, url);
  64. message.Content = content;
  65. var response = await client.SendAsync(message, token);
  66. response.EnsureSuccessStatusCode();
  67. var result = await response.Content.ReadAsStringAsync();
  68. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult>(result);
  69. return AjaxResult;
  70. }
  71. public static async Task<AjaxResult<T>> GetRequestAsync<T>(string url, int timeoutSeconds = 60)
  72. {
  73. var handler = new HttpClientHandler() { UseCookies = false };
  74. HttpClient client = new HttpClient(handler);
  75. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  76. var response = await client.GetAsync(url);
  77. response.EnsureSuccessStatusCode();
  78. var result = await response.Content.ReadAsStringAsync();
  79. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  80. return AjaxResult;
  81. }
  82. /// <summary>
  83. ///
  84. /// </summary>
  85. /// <param name="baseUrl"></param>
  86. /// <param name="remoteFileName"></param>
  87. /// <param name="localFile"></param>
  88. /// <param name="timeoutSeconds"></param>
  89. /// <returns></returns>
  90. public static async Task<bool> DownloadFileAsync(string baseUrl, string remoteFileName, string localFile, int timeoutSeconds = 30)
  91. {
  92. baseUrl = baseUrl.Replace("/api", "");
  93. if (!baseUrl.EndsWith("/"))
  94. baseUrl += "/";
  95. var server = new Uri(baseUrl + $"wwwroot/{remoteFileName}");
  96. var httpClient = new HttpClient();
  97. httpClient.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  98. var responseMessage = await httpClient.GetAsync(server);
  99. if (responseMessage.IsSuccessStatusCode)
  100. {
  101. using (var fs = File.Create(localFile))
  102. {
  103. // 获取结果,并转成 stream 保存到本地。
  104. var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
  105. streamFromService.CopyTo(fs);
  106. }
  107. return true;
  108. }
  109. else
  110. return false;
  111. }
  112. /// <summary>
  113. /// 上传文件,wav文件会自动去掉44字节头
  114. /// </summary>
  115. /// <param name="localFile"></param>
  116. /// <param name="baseUrl"></param>
  117. /// <param name="timeoutSeconds"></param>
  118. /// <param name="token"></param>
  119. /// <returns></returns>
  120. public static async Task<string> UploadFileAsync(string localFile, string baseUrl, int timeoutSeconds = 30, CancellationToken token = default)
  121. {
  122. string uploadUrl = baseUrl;
  123. if (baseUrl.EndsWith("/"))
  124. uploadUrl += "File/UploadFileAsync";
  125. else
  126. uploadUrl += "/File/UploadFileAsync";
  127. try
  128. {
  129. // 添加文件内容到 MultipartFormDataContent
  130. FileInfo info = new FileInfo(localFile);
  131. bool isWav = info.Extension.ToLower() == ".wav";
  132. byte[] fileBytes = File.ReadAllBytes(localFile);
  133. if (isWav)
  134. {
  135. fileBytes = fileBytes.Skip(44).ToArray();//wav文件有44字节头
  136. }
  137. MultipartFormDataContent content = new MultipartFormDataContent();
  138. ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
  139. content.Add(fileContent, "file", Path.GetFileName(localFile));
  140. var handler = new HttpClientHandler() { UseCookies = false };
  141. HttpClient client = new HttpClient(handler);
  142. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  143. var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
  144. message.Content = content;
  145. var response = await client.SendAsync(message, token);
  146. response.EnsureSuccessStatusCode();
  147. var result = await response.Content.ReadAsStringAsync();
  148. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<string>>(result);
  149. if (AjaxResult.code == 200)
  150. {
  151. return AjaxResult.data;
  152. }
  153. else
  154. {
  155. throw new Exception(AjaxResult.msg);
  156. }
  157. }
  158. catch (TaskCanceledException)
  159. {
  160. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}超时!");
  161. }
  162. catch(Exception ex)
  163. {
  164. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!",ex);
  165. }
  166. }
  167. /// <summary>
  168. /// 删除文件
  169. /// </summary>
  170. /// <param name="files">要删除的文件</param>
  171. /// <param name="baseUrl">baseUrl</param>
  172. /// <returns></returns>
  173. public static async Task<int> DeleteFileAsync(string[] files, string baseUrl)
  174. {
  175. FileDeleteDto dto = new FileDeleteDto()
  176. {
  177. Files = files.ToList()
  178. };
  179. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  180. var handler = new HttpClientHandler() { UseCookies = false };
  181. HttpClient client = new HttpClient(handler);
  182. client.Timeout = TimeSpan.FromSeconds(30);
  183. var message = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/File/DeleteFiles");
  184. message.Content = content;
  185. var response = await client.SendAsync(message);
  186. response.EnsureSuccessStatusCode();
  187. var result = await response.Content.ReadAsStringAsync();
  188. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<int>>(result);
  189. return AjaxResult.data;
  190. }
  191. /// <summary>
  192. /// 删除文件
  193. /// </summary>
  194. /// <param name="files">要删除的文件</param>
  195. /// <param name="baseUrl">baseUrl</param>
  196. /// <returns></returns>
  197. public static async Task<int> DeleteFileAsync(string baseUrl, params string[] files)
  198. {
  199. FileDeleteDto dto = new FileDeleteDto()
  200. {
  201. Files = files.ToList()
  202. };
  203. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  204. var handler = new HttpClientHandler() { UseCookies = false };
  205. HttpClient client = new HttpClient(handler);
  206. client.Timeout = TimeSpan.FromSeconds(30);
  207. var message = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/File/DeleteFiles");
  208. message.Content = content;
  209. var response = await client.SendAsync(message);
  210. response.EnsureSuccessStatusCode();
  211. var result = await response.Content.ReadAsStringAsync();
  212. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<int>>(result);
  213. return AjaxResult.data;
  214. }
  215. }
  216. /// <summary>
  217. /// Http接口返回泛型对象
  218. /// </summary>
  219. public class AjaxResult<T>
  220. {
  221. /// <summary>
  222. /// 返回对象
  223. /// </summary>
  224. public T data { get; set; }
  225. /// <summary>
  226. /// 返回消息
  227. /// </summary>
  228. public string msg { get; set; } = "ok";
  229. /// <summary>
  230. /// 状态码.成功=200,失败=0
  231. /// </summary>
  232. public int code { get; set; } = 200;
  233. }
  234. /// <summary>
  235. /// Http接口返回对象
  236. /// </summary>
  237. public class AjaxResult
  238. {
  239. /// <summary>
  240. /// 返回对象
  241. /// </summary>
  242. public object data { get; set; }
  243. /// <summary>
  244. /// 返回消息
  245. /// </summary>
  246. public string msg { get; set; } = "ok";
  247. /// <summary>
  248. /// 状态码.成功=200,失败=0
  249. /// </summary>
  250. public int code { get; set; } = 200;
  251. }