|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- 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<HttpHelper> _logger;
-
- public HttpHelper(IHttpClientFactory httpClientFactory, ILogger<HttpHelper> 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<string?> HttpToGetAsync(string url)
- {
- return await HttpToGetAsync(url, new List<KeyValuePair<string, string>>());
- }
-
- public async Task<string?> HttpToGetAsync(string url, List<KeyValuePair<string, string>> 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<string?> HttpToPostAsync(string url, object data)
- {
- return await HttpToPostAsync(url, data, new List<KeyValuePair<string, string>>());
- }
-
- public async Task<string?> HttpToPostAsync(string url, object data, List<KeyValuePair<string, string>> 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;
- }
- }
- /// <summary>
- /// Authorization 的 Base64 加密
- /// </summary>
- /// <param name="username"></param>
- /// <param name="password"></param>
- /// <returns></returns>
- 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);
- }
- }
- }
|