HttpHelper.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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.Tasks;
  10. using XdCxRhDw.Dto;
  11. namespace XdCxRhDW.Core
  12. {
  13. public class HttpHelper
  14. {
  15. public static async Task<AjaxResult<T>> PostRequestAsync<T>(string url, object dto, int timeoutSeconds = 30)
  16. {
  17. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  18. var handler = new HttpClientHandler() { UseCookies = false };
  19. HttpClient client = new HttpClient(handler);
  20. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  21. var message = new HttpRequestMessage(HttpMethod.Post, url);
  22. message.Content = content;
  23. var response = await client.SendAsync(message);
  24. response.EnsureSuccessStatusCode();
  25. var result = await response.Content.ReadAsStringAsync();
  26. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  27. return AjaxResult;
  28. }
  29. public static async Task<bool> DownloadFileAsync(string baseUrl,string remoteFileName, string localFile, int timeoutSeconds = 30)
  30. {
  31. if (!baseUrl.EndsWith("/"))
  32. baseUrl += "/";
  33. var server = new Uri(baseUrl + $"wwwroot/{remoteFileName}");
  34. var httpClient = new HttpClient();
  35. httpClient.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  36. var responseMessage = await httpClient.GetAsync(server);
  37. if (responseMessage.IsSuccessStatusCode)
  38. {
  39. using (var fs = File.Create(localFile))
  40. {
  41. // 获取结果,并转成 stream 保存到本地。
  42. var streamFromService = await responseMessage.Content.ReadAsStreamAsync();
  43. streamFromService.CopyTo(fs);
  44. }
  45. return true;
  46. }
  47. else
  48. return false;
  49. }
  50. /// <summary>
  51. /// 上传文件,wav文件会自动去掉44字节头
  52. /// </summary>
  53. /// <param name="localFile"></param>
  54. /// <param name="uploadUrl"></param>
  55. /// <param name="timeoutSeconds"></param>
  56. /// <returns></returns>
  57. /// <exception cref="Exception"></exception>
  58. public static async Task<string> UploadFileAsync(string localFile, string uploadUrl, int timeoutSeconds = 30)
  59. {
  60. try
  61. {
  62. // 添加文件内容到 MultipartFormDataContent
  63. FileInfo info = new FileInfo(localFile);
  64. bool isWav = info.Extension.ToLower() == ".wav";
  65. byte[] fileBytes = File.ReadAllBytes(localFile);
  66. if (isWav)
  67. {
  68. fileBytes = fileBytes.Skip(44).ToArray();//wav文件有44字节头
  69. }
  70. MultipartFormDataContent content = new MultipartFormDataContent();
  71. ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
  72. content.Add(fileContent, "file", Path.GetFileName(localFile));
  73. var handler = new HttpClientHandler() { UseCookies = false };
  74. HttpClient client = new HttpClient(handler);
  75. client.Timeout = TimeSpan.FromSeconds(timeoutSeconds);
  76. var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
  77. message.Content = content;
  78. var response = await client.SendAsync(message);
  79. response.EnsureSuccessStatusCode();
  80. var result = await response.Content.ReadAsStringAsync();
  81. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<FileUploadResDto>>(result);
  82. if (AjaxResult.code == 200)
  83. {
  84. return AjaxResult.data.FileName;
  85. }
  86. else
  87. {
  88. throw new Exception(AjaxResult.msg);
  89. }
  90. }
  91. catch
  92. {
  93. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!");
  94. }
  95. }
  96. }
  97. }