HttpHelper.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Business.Core.Utilities
  7. {
  8. public class HttpHelper
  9. {
  10. public static string HttpGet(string url, Dictionary<string, string>? headers = null)
  11. {
  12. HttpClient client = new HttpClient();
  13. if (headers != null)
  14. {
  15. foreach (var header in headers)
  16. {
  17. client.DefaultRequestHeaders.Add(header.Key, header.Value);
  18. }
  19. }
  20. try
  21. {
  22. byte[] resultBytes = client.GetByteArrayAsync(url).Result;
  23. return Encoding.UTF8.GetString(resultBytes);
  24. }
  25. catch
  26. {
  27. return string.Empty;
  28. }
  29. }
  30. public static string HttpPost(string url, string postData, Dictionary<string, string>? headers = null, string contentType = "", int timeout = 0, Encoding? encoding = null)
  31. {
  32. HttpClient client = new HttpClient();
  33. if (headers != null)
  34. {
  35. foreach (var header in headers)
  36. {
  37. client.DefaultRequestHeaders.Add(header.Key, header.Value);
  38. }
  39. }
  40. HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8);
  41. if (!string.IsNullOrWhiteSpace(contentType))
  42. {
  43. content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
  44. }
  45. try
  46. {
  47. using HttpResponseMessage responseMessage = client.PostAsync(url, content).Result;
  48. byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
  49. return Encoding.UTF8.GetString(resultBytes);
  50. }
  51. catch
  52. {
  53. return string.Empty;
  54. }
  55. }
  56. }
  57. }