LJHttpUtil.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using JLHHJSvr.LJException;
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Net.Mime;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace JLHHJSvr.LJFramework.Tools
  14. {
  15. public class LJHttpUtil
  16. {
  17. private static readonly HttpClient httpClient = new HttpClient();
  18. private const string ContentType = "application/json";
  19. public static JObject PostRequest(string url, JObject requestObj)
  20. {
  21. var jsonStr = requestObj.ToString();
  22. var content = new StringContent(jsonStr, Encoding.UTF8, ContentType);
  23. try
  24. {
  25. using (var response = httpClient.PostAsync(url, content).Result)
  26. {
  27. response.EnsureSuccessStatusCode();
  28. var responseBody = response.Content.ReadAsStringAsync().Result;
  29. try
  30. {
  31. var result = JsonConvert.DeserializeObject<JObject>(responseBody);
  32. return result;
  33. }
  34. catch (JsonReaderException e)
  35. {
  36. throw new LJCommonException($"JSON 反序列化失败:{e.Message}\r\n响应体:{responseBody}");
  37. }
  38. }
  39. }
  40. catch (HttpRequestException e)
  41. {
  42. throw new HttpRequestException($"请求错误:{e.Message}", e);
  43. }
  44. }
  45. }
  46. }