HttpHelper.cs 3.0 KB

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