using Admin.Core.Api.PLTBusiness.Entity; using Admin.Core.Common; using Admin.Core.IService; using Admin.Core.PlcServer; using Admin.Core.Service; using log4net; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using NPOI.HSSF.Record; using RabbitMQ.Client; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Security.Policy; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace Admin.Core.Api.PLTBusiness { public class HttpService : BackgroundService { private readonly log4net.ILog log = LogManager.GetLogger(typeof(HttpService)); private readonly IServiceScopeFactory _scopeFactory; private readonly IHttpClientFactory _httpClientFactory; private readonly Ixl_recipeServices _xlrecipeServices; private readonly string _host = "http://192.168.111.141:8090"; private string _token; private int _tokenExpirationTime = 0; public HttpService(IHttpClientFactory httpClientFactory, IServiceScopeFactory scopeFactory, Ixl_recipeServices xlrecipeServices) { _httpClientFactory = httpClientFactory; _scopeFactory = scopeFactory; _xlrecipeServices = xlrecipeServices; } /// /// 循环执行的服务 /// /// /// protected async override Task ExecuteAsync(CancellationToken stoppingToken) { int second = 1000 * 10; using var scope = _scopeFactory.CreateScope(); var services = scope.ServiceProvider; var xlBusiness = services.GetService(); while (!stoppingToken.IsCancellationRequested) { //执行任务 //log.Info($"{DateTime.Now}"); if (_tokenExpirationTime == 0) { if (await GetToken()) { log.Info("Token Get! Value:" + _token); } else { log.Error("Token Get Falied"); } } else if (_tokenExpirationTime <= 86400) { RefreshToken(); } else { _tokenExpirationTime = _tokenExpirationTime - (second / 1000); } try { //物料信息同步 if (_token.IsNotEmptyOrNull()) { await xlBusiness.InsertNewMaterialData(await GetMaterialDataPageList()); //await _xlrecipeServices.xlUpdateOrAdd(); } else { log.Error("No Token!!!"); } } catch (Exception ex) { log.Error("Error: " + ex); } await Task.Delay(second); } } #region Mes信息拉取 /// /// 分页拉取所有Mes物料信息 /// /// private async Task> GetMaterialDataPageList() { int pageSize = 200; int pageIndex = 0; int pageCount = 1; string orgCode = "Mesnac"; List allMaterials = new List(); Dictionary _pageInfo = new Dictionary() { {"pageIndex", 200}, {"pageSize", 0}, {"orgCode", "Mesnac"}, }; try { do { string body = JsonSerializer.Serialize(_pageInfo); string materialJson = await PostAsync(_host + "/qtn/api/q7/com/inventory/page", body, "application/json", "application/json", new Dictionary { { "token", _token } }, 10); ResponseRoot responseRoot = JsonSerializer.Deserialize>(materialJson); if (responseRoot == null) { log.Error("物料信息拉取失败!"); return null; } if (responseRoot.code != 200) { log.Error("ERROR 状态码:" + responseRoot.code); return null; } pageCount = responseRoot.Data.pageCount; pageIndex = responseRoot.Data.pageIndex; allMaterials.AddRange(responseRoot.Data.recordList); pageIndex = pageIndex + 1; } while (pageIndex < pageSize); } catch (Exception ex) { log.Error("Mes物料信息拉取失败 Error: " + ex); return null; } return allMaterials; } /// /// 分页拉取所有MesBom配方信息 /// /// private async Task> GetRecipeDataPageList() { int pageSize = 200; int pageIndex = 0; int pageCount = 1; string orgCode = "Mesnac"; List allBoms = new List(); Dictionary _pageInfo = new Dictionary() { {"pageIndex", 200}, {"pageSize", 0}, {"orgCode", "Mesnac"}, }; try { do { string body = JsonSerializer.Serialize(_pageInfo); string bomJson = await PostAsync(_host + "/qtn/api/q7/com/bom/page", body, "application/json", "application/json", new Dictionary { { "token", _token } }, 10); ResponseRoot responseRoot = JsonSerializer.Deserialize>(bomJson); if (responseRoot == null) { log.Error("Bom信息拉取失败!"); return null; } if (responseRoot.code != 200) { log.Error("ERROR 状态码:" + responseRoot.code); return null; } pageCount = responseRoot.Data.pageCount; pageIndex = responseRoot.Data.pageIndex; allBoms.AddRange(responseRoot.Data.recordList); pageIndex = pageIndex + 1; } while (pageIndex < pageSize); } catch (Exception ex) { log.Error("MesBom信息拉取失败 Error: " + ex); return null; } return allBoms; } #endregion #region Token获取 /// /// 获取Token /// private async Task GetToken() { Dictionary _tokenDictionary = new Dictionary() { {"authCode", "QT_XXX"}, {"appid", "q7cloud_XXX"}, {"secret", "f434eab8b9652524dc719e33f4ff255a45570XXX"} }; try { string body = JsonSerializer.Serialize(_tokenDictionary); string tokenJson = await PostAsync(_host + "/qtn/api/auth/token", body, "application/json", "application/json", null, 10); ResponseRoot responseRoot = JsonSerializer.Deserialize>(tokenJson); if (responseRoot == null) { log.Error("Token获取失败!"); return false; } if (responseRoot.code != 200) { log.Error("ERROR 状态码:" + responseRoot.code); return false; } _token = responseRoot.Data.token; _tokenExpirationTime = responseRoot.Data.expiration; log.Info("Token获取成功:" + _token + "超时时间:" + _tokenExpirationTime); return true; } catch (Exception ex) { log.Error("Token获取失败 ERROR: " + ex.ToString()); return false; } } /// /// 刷新Token /// private async Task RefreshToken() { try { string tokenJson = await PostAsync(_host + "/qtn/api/auth/token/refresh", "" , "application/json", "application/x-www-form-urlencoded" , new Dictionary() { { "token", _token } }, 10); ResponseRoot responseRoot = JsonSerializer.Deserialize>(tokenJson); if (responseRoot == null) { log.Error("Token更新失败!"); return false; } if (responseRoot.code != 200) { log.Error("ERROR 状态码:" + responseRoot.code); return false; } _token = responseRoot.Data.token; _tokenExpirationTime = responseRoot.Data.expiration; log.Info("Token更新成功:" + _token + "超时时间:" + _tokenExpirationTime); return true; } catch (Exception ex) { log.Error("Token更新失败 ERROR: " + ex.ToString()); return false; } } #endregion #region HTTP操作 /// /// 发起POST异步请求 /// /// 请求地址 /// POST提交的内容 /// POST内容的媒体类型,如:application/xml、application/json /// HTTP响应上的content-type内容头的值,如:application/xml、application/json、application/text、application/x-www-form-urlencoded等 /// 请求头信息 /// 请求超时时间,单位秒 /// 返回string private async Task PostAsync(string url, string body, string bodyMediaType = null, string responseContentType = null, Dictionary headers = null, int timeOut = 30) { try { var hostName = GetHostName(url); using (HttpClient client = _httpClientFactory.CreateClient(hostName)) { client.Timeout = TimeSpan.FromSeconds(timeOut); if (headers?.Count > 0) { foreach (string key in headers.Keys) { client.DefaultRequestHeaders.Add(key, headers[key]); } } StringContent content = new StringContent(body, System.Text.Encoding.UTF8, mediaType: bodyMediaType); if (!string.IsNullOrWhiteSpace(responseContentType)) { content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(responseContentType); } using (HttpResponseMessage response = await client.PostAsync(url, content)) { if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); return responseString; } else { return string.Empty; } } } } catch (Exception ex) { log.Error($"Post请求失败 URL:{url} ERROR: {ex.ToString()} Time: {DateTime.Now}"); throw; } } /// /// 发起GET异步请求 /// /// 返回类型 /// 请求地址 /// 请求头信息 /// 请求超时时间,单位秒 /// 返回string private async Task GetAsync(string url, Dictionary headers = null, int timeOut = 30) { try { var hostName = GetHostName(url); using (HttpClient client = _httpClientFactory.CreateClient(hostName)) { client.Timeout = TimeSpan.FromSeconds(timeOut); if (headers?.Count > 0) { foreach (string key in headers.Keys) { client.DefaultRequestHeaders.Add(key, headers[key]); } } using (HttpResponseMessage response = await client.GetAsync(url)) { if (response.IsSuccessStatusCode) { string responseString = await response.Content.ReadAsStringAsync(); return responseString; } else { return string.Empty; } } } } catch (Exception ex) { log.Error($"Get请求失败 URL:{url} ERROR: {ex.ToString()} Time: {DateTime.Now}"); throw; } } private async Task Post(string url, Dictionary headers = null) { var hostName = GetHostName(url); // 创建 HttpClient 实例 var client = _httpClientFactory.CreateClient(hostName); // 定义要发送的对象 //var data = new //{ // Name = "John Doe", // Age = 30, // Email = "john.doe@example.com" //}; // 序列化对象为 JSON var json = JsonSerializer.Serialize(headers); // 创建 HttpContent,设置内容为 JSON 格式 var content = new StringContent(json, Encoding.UTF8, "application/json"); // 发送 POST 请求 var response = await client.PostAsync(url, content); // 检查响应状态码 if (response.IsSuccessStatusCode) { // 读取响应内容 var responseBody = await response.Content.ReadAsStringAsync(); log.Info($"Response: {responseBody}"); } else { log.Error($"Error: {response.StatusCode}"); } } #endregion #region 私有函数 /// /// 获取请求的主机名 /// /// /// private static string GetHostName(string url) { if (!string.IsNullOrWhiteSpace(url)) { return url.Replace("https://", "").Replace("http://", "").Split('/')[0]; } else { return "AnyHost"; } } #endregion } }