HttpHelper.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. namespace EInk.Tools
  2. {
  3. public enum HttpResultCode
  4. {
  5. Ok,
  6. Fail,
  7. Error
  8. }
  9. public static class HttpHelper
  10. {
  11. public static (bool, string) Get(string url, int timeOut = 10)
  12. {
  13. try
  14. {
  15. using HttpClient client = new();
  16. client.Timeout = TimeSpan.FromSeconds(1000 * timeOut);
  17. HttpResponseMessage response = client.GetAsync(url).Result;
  18. response.EnsureSuccessStatusCode();
  19. string responseBody = response.Content.ReadAsStringAsync().Result;
  20. return (true, responseBody);
  21. }
  22. catch (HttpRequestException ex)
  23. {
  24. return (false, ex.Message);
  25. }
  26. }
  27. public static (bool, string) Post(string url, string inputData, int timeOut = 10)
  28. {
  29. try
  30. {
  31. using HttpClient client = new();
  32. client.Timeout = TimeSpan.FromSeconds(1000 * timeOut);
  33. HttpContent content = new StringContent(inputData, System.Text.Encoding.UTF8, "application/json");
  34. HttpResponseMessage response = client.PostAsync(url, content).Result;
  35. response.EnsureSuccessStatusCode();
  36. string responseBody = response.Content.ReadAsStringAsync().Result;
  37. return (true, responseBody);
  38. }
  39. catch (HttpRequestException ex)
  40. {
  41. return (false, ex.Message);
  42. }
  43. }
  44. public static (bool, string) Post(string url, int timeOut = 10)
  45. {
  46. return Post(url, "", timeOut);
  47. }
  48. }
  49. }