HttpHelper.cs 7.0 KB

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