HttpHelper.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net.Http;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using XdCxRhDw.Dto;
  9. namespace XdCxRhDW.Core
  10. {
  11. public class HttpHelper
  12. {
  13. /// <summary>
  14. ///
  15. /// </summary>
  16. /// <param name="url"></param>
  17. /// <param name="data"></param>
  18. /// <returns></returns>
  19. public static string PostRequest(string url, HttpContent data)
  20. {
  21. var handler = new HttpClientHandler() { UseCookies = false };
  22. HttpClient client = new HttpClient(handler);
  23. client.Timeout = TimeSpan.FromSeconds(10);
  24. var message = new HttpRequestMessage(HttpMethod.Post, url);
  25. message.Content = data;
  26. var response = client.SendAsync(message).Result;
  27. response.EnsureSuccessStatusCode();
  28. var result = response.Content.ReadAsStringAsync().Result;
  29. return result;
  30. }
  31. /// <summary>
  32. ///
  33. /// </summary>
  34. /// <typeparam name="T"></typeparam>
  35. /// <param name="url"></param>
  36. /// <param name="data"></param>
  37. /// <returns></returns>
  38. public static T PostRequest<T>(string url, HttpContent data)
  39. {
  40. var handler = new HttpClientHandler() { UseCookies = false };
  41. HttpClient client = new HttpClient(handler);
  42. client.Timeout = TimeSpan.FromSeconds(20);
  43. var message = new HttpRequestMessage(HttpMethod.Post, url);
  44. message.Content = data;
  45. var response = client.SendAsync(message).Result;
  46. response.EnsureSuccessStatusCode();
  47. var result = response.Content.ReadAsStringAsync().Result;
  48. var AjaxResult = JsonConvert.DeserializeObject<AjaxResult<T>>(result);
  49. if (AjaxResult.code == 200)
  50. {
  51. return AjaxResult.data;
  52. }
  53. else
  54. {
  55. throw new Exception(AjaxResult.msg);
  56. }
  57. }
  58. }
  59. }