HttpHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. /// <summary>
  16. ///
  17. /// </summary>
  18. /// <typeparam name="T"></typeparam>
  19. /// <param name="url"></param>
  20. /// <param name="dto">dto对象</param>
  21. /// <returns></returns>
  22. public static AjaxResult<T> PostRequest<T>(string url, object dto)
  23. {
  24. var content = new StringContent(JsonConvert.SerializeObject(dto), System.Text.Encoding.UTF8, "application/json");
  25. var handler = new HttpClientHandler() { UseCookies = false };
  26. HttpClient client = new HttpClient(handler);
  27. client.Timeout = TimeSpan.FromSeconds(20);
  28. var message = new HttpRequestMessage(HttpMethod.Post, url);
  29. message.Content = content;
  30. var response = client.SendAsync(message).Result;
  31. response.EnsureSuccessStatusCode();
  32. var result = response.Content.ReadAsStringAsync().Result;
  33. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  34. return AjaxResult;
  35. }
  36. public static string UploadFile(string localFile, string uploadUrl)
  37. {
  38. try
  39. {
  40. // 添加文件内容到 MultipartFormDataContent
  41. byte[] fileBytes = File.ReadAllBytes(localFile);
  42. MultipartFormDataContent content = new MultipartFormDataContent();
  43. ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
  44. content.Add(fileContent, "file", Path.GetFileName(localFile));
  45. var handler = new HttpClientHandler() { UseCookies = false };
  46. HttpClient client = new HttpClient(handler);
  47. client.Timeout = TimeSpan.FromSeconds(20);
  48. var message = new HttpRequestMessage(HttpMethod.Post, uploadUrl);
  49. message.Content = content;
  50. var response = client.SendAsync(message).Result;
  51. response.EnsureSuccessStatusCode();
  52. var result = response.Content.ReadAsStringAsync().Result;
  53. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<FileUploadResDto>>(result);
  54. if (AjaxResult.code == 200)
  55. {
  56. return AjaxResult.data.FileName;
  57. }
  58. else
  59. {
  60. throw new Exception(AjaxResult.msg);
  61. }
  62. }
  63. catch
  64. {
  65. throw new Exception($"上传文件{Path.GetFileName(localFile)}到{uploadUrl}失败!");
  66. }
  67. }
  68. }
  69. }