using Microsoft.Extensions.Logging; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace HealthMonitor.Common.helper { public class HttpHelper { private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger _logger; public HttpHelper(IHttpClientFactory httpClientFactory, ILogger logger) { _httpClientFactory = httpClientFactory; _logger = logger; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult!); } public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } public async Task HttpToGetAsync(string url) { return await HttpToGetAsync(url, new List>()); } public async Task HttpToGetAsync(string url, List> headers) { var client = _httpClientFactory.CreateClient(Consts.DEFAULT_HTTPCLIENT_NAME); if (headers != null && headers.Count > 0) //指定请求头 { headers.ForEach(e => { client.DefaultRequestHeaders.Add(e.Key, e.Value); }); } try { using (var response = await client.GetAsync(url).ConfigureAwait(false)) { if (!response.IsSuccessStatusCode) return null; else { var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return result; } } } catch (Exception ex) { _logger.LogError($"HttpToGetAsync发生异常, Msg:{ex.Message}\n{ex.StackTrace}"); return null; } } public async Task HttpToPostAsync(string url, object data) { return await HttpToPostAsync(url, data, new List>()); } public async Task HttpToPostAsync(string url, object data, List> headers) { if (data == null) return null; var client = _httpClientFactory.CreateClient(Consts.DEFAULT_HTTPCLIENT_NAME); if (headers != null && headers.Count > 0) //指定请求头 { headers.ForEach(e => { client.DefaultRequestHeaders.Add(e.Key, e.Value); }); } string? body; if (data is string) body = data as string; else body = JsonConvert.SerializeObject(data); try { using (var content = new StringContent(body!)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); using (var response = await client.PostAsync(url, content).ConfigureAwait(false)) { if (!response.IsSuccessStatusCode) return null; else { var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return result; } } } } catch (Exception ex) { _logger.LogError($"HttpToPostAsync发生异常, Msg:{ex.Message}\n{ex.StackTrace}"); return null; } } /// /// Authorization 的 Base64 加密 /// /// /// /// public string GetEncodedCredentials(string username, string password) { string mergedCredentials = string.Format("{0}:{1}", username, password); byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials); return Convert.ToBase64String(byteCredentials); } } }