HttpHelper.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. if (token != null && token.IsCancellationRequested)
  161. throw new TaskCanceledException();
  162. else
  163. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}超时!");
  164. }
  165. catch (Exception ex)
  166. {
  167. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!", ex);
  168. }
  169. }
  170. /// <summary>
  171. /// 删除文件
  172. /// </summary>
  173. /// <param name="files">要删除的文件</param>
  174. /// <param name="baseUrl">baseUrl</param>
  175. /// <returns></returns>
  176. public static async Task<int> DeleteFileAsync(string[] files, string baseUrl)
  177. {
  178. FileDeleteDto dto = new FileDeleteDto()
  179. {
  180. Files = files.ToList()
  181. };
  182. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  183. var handler = new HttpClientHandler() { UseCookies = false };
  184. HttpClient client = new HttpClient(handler);
  185. client.Timeout = TimeSpan.FromSeconds(30);
  186. var message = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/File/DeleteFiles");
  187. message.Content = content;
  188. var response = await client.SendAsync(message);
  189. response.EnsureSuccessStatusCode();
  190. var result = await response.Content.ReadAsStringAsync();
  191. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<int>>(result);
  192. return AjaxResult.data;
  193. }
  194. /// <summary>
  195. /// 删除文件
  196. /// </summary>
  197. /// <param name="files">要删除的文件</param>
  198. /// <param name="baseUrl">baseUrl</param>
  199. /// <returns></returns>
  200. public static async Task<int> DeleteFileAsync(string baseUrl, params string[] files)
  201. {
  202. FileDeleteDto dto = new FileDeleteDto()
  203. {
  204. Files = files.ToList()
  205. };
  206. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  207. var handler = new HttpClientHandler() { UseCookies = false };
  208. HttpClient client = new HttpClient(handler);
  209. client.Timeout = TimeSpan.FromSeconds(30);
  210. var message = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/File/DeleteFiles");
  211. message.Content = content;
  212. var response = await client.SendAsync(message);
  213. response.EnsureSuccessStatusCode();
  214. var result = await response.Content.ReadAsStringAsync();
  215. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<int>>(result);
  216. return AjaxResult.data;
  217. }
  218. }
  219. /// <summary>
  220. /// Http接口返回泛型对象
  221. /// </summary>
  222. public class AjaxResult<T>
  223. {
  224. /// <summary>
  225. /// 返回对象
  226. /// </summary>
  227. public T data { get; set; }
  228. /// <summary>
  229. /// 返回消息
  230. /// </summary>
  231. public string msg { get; set; } = "ok";
  232. /// <summary>
  233. /// 状态码.成功=200,失败=0
  234. /// </summary>
  235. public int code { get; set; } = 200;
  236. }
  237. /// <summary>
  238. /// Http接口返回对象
  239. /// </summary>
  240. public class AjaxResult
  241. {
  242. /// <summary>
  243. /// 返回对象
  244. /// </summary>
  245. public object data { get; set; }
  246. /// <summary>
  247. /// 返回消息
  248. /// </summary>
  249. public string msg { get; set; } = "ok";
  250. /// <summary>
  251. /// 状态码.成功=200,失败=0
  252. /// </summary>
  253. public int code { get; set; } = 200;
  254. }