HttpHelper.cs 2.9 KB

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