IcsFromERPJob
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.1 KiB

4 months ago
3 months ago
3 months ago
3 months ago
  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.Net;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace ICSSoft.FromERP
  12. {
  13. public class HttpHelper
  14. {
  15. /// <summary>
  16. /// POST请求
  17. /// </summary>
  18. /// <param name="url">地址</param>
  19. /// <param name="requestJson">请求json</param>
  20. /// <param name="token">token</param>
  21. /// <returns></returns>
  22. public static async Task<T> HttpClientPost<T>(string url, string requestJson, string contentType = "application/json", string token = "") where T : new()
  23. {
  24. string result = string.Empty;
  25. Uri postUrl = new Uri(url);
  26. using (HttpContent httpContent = new StringContent(requestJson, System.Text.Encoding.UTF8, contentType))
  27. {
  28. //使用注入的httpclientfactory获取client
  29. using (var httpClient = new HttpClient())
  30. {
  31. //设置请求头
  32. //设置超时时间
  33. if (!string.IsNullOrEmpty(token))
  34. httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
  35. httpClient.Timeout = new TimeSpan(0, 0, 60);
  36. var res = httpClient.PostAsync(url, httpContent).Result;
  37. res.EnsureSuccessStatusCode();
  38. result = res.Content.ReadAsStringAsync().Result;
  39. return JsonConvert.DeserializeObject<T>(result);
  40. }
  41. }
  42. }
  43. public static async Task<T> HttpClientGet<T>(string url) where T : new()
  44. {
  45. using (HttpClient httpClient = new HttpClient())
  46. {
  47. HttpResponseMessage res = httpClient.GetAsync(url).Result;
  48. res.EnsureSuccessStatusCode();
  49. var t = res.Content.ReadAsStringAsync().Result;
  50. return JsonConvert.DeserializeObject<T>(t);
  51. };
  52. }
  53. }
  54. }