HttpHelper.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net.Http;
  6. using System.Security.Policy;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. /// <summary>
  11. /// http调用帮助类
  12. /// </summary>
  13. public class HttpHelper
  14. {
  15. /// <summary>
  16. /// 文件删除模型
  17. /// </summary>
  18. class FileDeleteDto
  19. {
  20. /// <summary>
  21. /// 要删除的服务器上的文件名称
  22. /// </summary>
  23. public List<string> Files { get; set; }
  24. }
  25. /// <summary>
  26. ///
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <param name="url"></param>
  30. /// <param name="dto"></param>
  31. /// <param name="timeoutSeconds"></param>
  32. /// <param name="token"></param>
  33. /// <returns></returns>
  34. public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto, int timeoutSeconds = 60, CancellationToken token = default)
  35. {
  36. var content = new StringContent(dto.ToJson(), System.Text.Encoding.UTF8, "application/json");
  37. var handler = new HttpClientHandler() { UseCookies = false };
  38. using (HttpClient client = new HttpClient(handler))
  39. {
  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 = result.ToObj<AjaxResult<T>>();
  47. return AjaxResult;
  48. }
  49. }
  50. /// <summary>
  51. ///
  52. /// </summary>
  53. /// <param name="url"></param>
  54. /// <param name="dto"></param>
  55. /// <param name="token"></param>
  56. /// <param name="timeoutSeconds"></param>
  57. /// <returns></returns>
  58. public static async Task<AjaxResult> PostRequestAsync(string url, object dto, int timeoutSeconds = 60, CancellationToken token = default)
  59. {
  60. var content = new StringContent(dto.ToJson(), System.Text.Encoding.UTF8, "application/json");
  61. var handler = new HttpClientHandler() { UseCookies = false };
  62. using (HttpClient client = new HttpClient(handler))
  63. {
  64. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  65. var message = new HttpRequestMessage(HttpMethod.Post, url);
  66. message.Content = content;
  67. var response = await client.SendAsync(message, token);
  68. response.EnsureSuccessStatusCode();
  69. var result = await response.Content.ReadAsStringAsync();
  70. var AjaxResult = result.ToObj<AjaxResult>();
  71. return AjaxResult;
  72. }
  73. }
  74. public static async Task<AjaxResult<T>> GetRequestAsync<T>(string url, int timeoutSeconds = 60)
  75. {
  76. var handler = new HttpClientHandler() { UseCookies = false };
  77. using (HttpClient client = new HttpClient(handler))
  78. {
  79. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  80. var response = await client.GetAsync(url);
  81. response.EnsureSuccessStatusCode();
  82. var result = await response.Content.ReadAsStringAsync();
  83. var AjaxResult = result.ToObj<AjaxResult<T>>();
  84. return AjaxResult;
  85. }
  86. }
  87. /// <summary>
  88. ///
  89. /// </summary>
  90. /// <param name="url"></param>
  91. /// <param name="remoteFileName"></param>
  92. /// <param name="localFile"></param>
  93. /// <param name="timeoutSeconds"></param>
  94. /// <returns></returns>
  95. public static async Task<bool> DownloadFileAsync(string url, string remoteFileName, string localFile, int timeoutSeconds = 30)
  96. {
  97. var server = new Uri($"{url}?filename={remoteFileName}");
  98. using (var httpClient = new HttpClient())
  99. {
  100. httpClient.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  101. var responseMessage = await httpClient.GetAsync(server);
  102. if (responseMessage.IsSuccessStatusCode)
  103. {
  104. var dir = Path.GetDirectoryName(localFile);
  105. Directory.CreateDirectory(dir);
  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. }
  118. /// <summary>
  119. /// 上传文件,wav文件会自动去掉44字节头
  120. /// </summary>
  121. /// <param name="localFile"></param>
  122. /// <param name="baseUrl"></param>
  123. /// <param name="timeoutSeconds"></param>
  124. /// <param name="token"></param>
  125. /// <returns></returns>
  126. public static async Task<string> UploadFileAsync(string localFile, string baseUrl, int timeoutSeconds = 30, CancellationToken token = default)
  127. {
  128. string uploadUrl = baseUrl;
  129. if (baseUrl.EndsWith("/"))
  130. uploadUrl += "File/UploadFileAsync";
  131. else
  132. uploadUrl += "/File/UploadFileAsync";
  133. try
  134. {
  135. // 添加文件内容到 MultipartFormDataContent
  136. FileInfo info = new FileInfo(localFile);
  137. bool isWav = info.Extension.ToLower() == ".wav";
  138. byte[] fileBytes = File.ReadAllBytes(localFile);
  139. if (isWav)
  140. {
  141. fileBytes = fileBytes.Skip(44).ToArray();//wav文件有44字节头
  142. }
  143. MultipartFormDataContent content = new MultipartFormDataContent();
  144. ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
  145. content.Add(fileContent, "file", Path.GetFileName(localFile));
  146. var handler = new HttpClientHandler() { UseCookies = false };
  147. using (HttpClient client = new HttpClient(handler))
  148. {
  149. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  150. var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
  151. message.Content = content;
  152. var response = await client.SendAsync(message, token);
  153. response.EnsureSuccessStatusCode();
  154. var result = await response.Content.ReadAsStringAsync();
  155. var AjaxResult = result.ToObj<AjaxResult<string>>();
  156. if (AjaxResult.code == 200)
  157. {
  158. return AjaxResult.data;
  159. }
  160. else
  161. {
  162. throw new Exception(AjaxResult.msg);
  163. }
  164. }
  165. }
  166. catch (TaskCanceledException)
  167. {
  168. if (token.IsCancellationRequested)
  169. throw new TaskCanceledException();
  170. else
  171. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}超时!");
  172. }
  173. catch (Exception ex)
  174. {
  175. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!", ex);
  176. }
  177. }
  178. /// <summary>
  179. /// 删除文件
  180. /// </summary>
  181. /// <param name="files">要删除的文件</param>
  182. /// <param name="baseUrl">baseUrl</param>
  183. /// <returns></returns>
  184. public static async Task<int> DeleteFileAsync(string[] files, string baseUrl)
  185. {
  186. FileDeleteDto dto = new FileDeleteDto()
  187. {
  188. Files = files.ToList()
  189. };
  190. var content = new StringContent(dto.ToJson(), System.Text.Encoding.UTF8, "application/json");
  191. var handler = new HttpClientHandler() { UseCookies = false };
  192. using (HttpClient client = new HttpClient(handler))
  193. {
  194. client.Timeout = TimeSpan.FromSeconds(30);
  195. var message = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/File/DeleteFiles");
  196. message.Content = content;
  197. var response = await client.SendAsync(message);
  198. response.EnsureSuccessStatusCode();
  199. var result = await response.Content.ReadAsStringAsync();
  200. var AjaxResult = result.ToObj<AjaxResult<int>>();
  201. return AjaxResult.data;
  202. }
  203. }
  204. /// <summary>
  205. /// 删除文件
  206. /// </summary>
  207. /// <param name="files">要删除的文件</param>
  208. /// <param name="baseUrl">baseUrl</param>
  209. /// <returns></returns>
  210. public static async Task<int> DeleteFileAsync(string baseUrl, params string[] files)
  211. {
  212. FileDeleteDto dto = new FileDeleteDto()
  213. {
  214. Files = files.ToList()
  215. };
  216. var content = new StringContent(dto.ToJson(), System.Text.Encoding.UTF8, "application/json");
  217. var handler = new HttpClientHandler() { UseCookies = false };
  218. using (HttpClient client = new HttpClient(handler))
  219. {
  220. client.Timeout = TimeSpan.FromSeconds(30);
  221. var message = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/File/DeleteFiles");
  222. message.Content = content;
  223. var response = await client.SendAsync(message);
  224. response.EnsureSuccessStatusCode();
  225. var result = await response.Content.ReadAsStringAsync();
  226. var AjaxResult = result.ToObj<AjaxResult<int>>();
  227. return AjaxResult.data;
  228. }
  229. }
  230. }
  231. /// <summary>
  232. /// Http接口返回泛型对象
  233. /// </summary>
  234. public class AjaxResult<T>
  235. {
  236. /// <summary>
  237. /// 返回对象
  238. /// </summary>
  239. public T data { get; set; }
  240. /// <summary>
  241. /// 返回消息
  242. /// </summary>
  243. public string msg { get; set; } = "ok";
  244. /// <summary>
  245. /// 状态码.成功=200,失败=0
  246. /// </summary>
  247. public int code { get; set; } = 200;
  248. }
  249. /// <summary>
  250. /// Http接口返回对象
  251. /// </summary>
  252. public class AjaxResult
  253. {
  254. /// <summary>
  255. /// 返回对象
  256. /// </summary>
  257. public object data { get; set; }
  258. /// <summary>
  259. /// 返回消息
  260. /// </summary>
  261. public string msg { get; set; } = "ok";
  262. /// <summary>
  263. /// 状态码.成功=200,失败=0
  264. /// </summary>
  265. public int code { get; set; } = 200;
  266. }