HttpHelper.cs 9.5 KB

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