HttpHelper.cs 6.4 KB

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