Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

130 linhas
4.5KB

  1. using Microsoft.Extensions.Logging;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Net.Http.Headers;
  9. using System.Net.Security;
  10. using System.Security.Cryptography.X509Certificates;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. namespace HealthMonitor.Common.helper
  14. {
  15. public class HttpHelper
  16. {
  17. private readonly IHttpClientFactory _httpClientFactory;
  18. private readonly ILogger<HttpHelper> _logger;
  19. public HttpHelper(IHttpClientFactory httpClientFactory, ILogger<HttpHelper> logger)
  20. {
  21. _httpClientFactory = httpClientFactory;
  22. _logger = logger;
  23. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult!);
  24. }
  25. public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  26. {
  27. return true;
  28. }
  29. public async Task<string?> HttpToGetAsync(string url)
  30. {
  31. return await HttpToGetAsync(url, new List<KeyValuePair<string, string>>());
  32. }
  33. public async Task<string?> HttpToGetAsync(string url, List<KeyValuePair<string, string>> headers)
  34. {
  35. var client = _httpClientFactory.CreateClient(Consts.DEFAULT_HTTPCLIENT_NAME);
  36. if (headers != null && headers.Count > 0) //指定请求头
  37. {
  38. headers.ForEach(e =>
  39. {
  40. client.DefaultRequestHeaders.Add(e.Key, e.Value);
  41. });
  42. }
  43. try
  44. {
  45. using (var response = await client.GetAsync(url).ConfigureAwait(false))
  46. {
  47. if (!response.IsSuccessStatusCode) return null;
  48. else
  49. {
  50. var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  51. return result;
  52. }
  53. }
  54. }
  55. catch (Exception ex)
  56. {
  57. _logger.LogError($"HttpToGetAsync发生异常, Msg:{ex.Message}\n{ex.StackTrace}");
  58. return null;
  59. }
  60. }
  61. public async Task<string?> HttpToPostAsync(string url, object data)
  62. {
  63. return await HttpToPostAsync(url, data, new List<KeyValuePair<string, string>>());
  64. }
  65. public async Task<string?> HttpToPostAsync(string url, object data, List<KeyValuePair<string, string>> headers)
  66. {
  67. if (data == null) return null;
  68. var client = _httpClientFactory.CreateClient(Consts.DEFAULT_HTTPCLIENT_NAME);
  69. if (headers != null && headers.Count > 0) //指定请求头
  70. {
  71. headers.ForEach(e =>
  72. {
  73. client.DefaultRequestHeaders.Add(e.Key, e.Value);
  74. });
  75. }
  76. string? body;
  77. if (data is string) body = data as string;
  78. else body = JsonConvert.SerializeObject(data);
  79. try
  80. {
  81. using (var content = new StringContent(body!))
  82. {
  83. content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  84. using (var response = await client.PostAsync(url, content).ConfigureAwait(false))
  85. {
  86. if (!response.IsSuccessStatusCode) return null;
  87. else
  88. {
  89. var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  90. return result;
  91. }
  92. }
  93. }
  94. }
  95. catch (Exception ex)
  96. {
  97. _logger.LogError($"HttpToPostAsync发生异常, Msg:{ex.Message}\n{ex.StackTrace}");
  98. return null;
  99. }
  100. }
  101. /// <summary>
  102. /// Authorization 的 Base64 加密
  103. /// </summary>
  104. /// <param name="username"></param>
  105. /// <param name="password"></param>
  106. /// <returns></returns>
  107. public string GetEncodedCredentials(string username, string password)
  108. {
  109. string mergedCredentials = string.Format("{0}:{1}", username, password);
  110. byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
  111. return Convert.ToBase64String(byteCredentials);
  112. }
  113. }
  114. }