HttpHelper.cs 7.1 KB

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