using DBEntity; using IvfTl.Control.Entity.DTO; using IvfTl.Control.Entity.DTO.ApiResutlDatas; using IvfTl.Control.Entity.GlobalEntitys; using IvfTl.Control.Entity.GlobalEnums; using Newtonsoft.Json; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Principal; using System.Text; namespace IvfTl.Control.Services.HttpServices { public class HttpService { public event Action ErrorLogEvent; public event Action ExceptionLogEvent; private string token = null; private string account = null; private string passWord = null; private HttpClient client = null; //我这边超时 private TimeSpan AsyncTimeout = new TimeSpan(0, 0, 10); //服务器超时 TimeSpan ServiceTimeout = new TimeSpan(0, 0, 12); public HttpService(string baseAddress) { client = new HttpClient() { BaseAddress = new Uri(baseAddress), Timeout = ServiceTimeout }; client.DefaultRequestHeaders.ExpectContinue = false; System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } private void ExLog(Exception ex, string name) { ExceptionLogEvent?.Invoke(ex, $"HttpService.{name}", null, LogEnum.RunException); } private void ErrorLog(string message, LogEnum logType) { ErrorLogEvent?.Invoke($"HttpService.{message}", logType); } public void AlarmApi(string tlSn, int houseSn, int wellSn, string alarmTypeKey, List paramList) { string funcName = "AlarmApi"; try { string url = "/api/tl/control/alarm/reportCloudAlarm"; string body = JsonConvert.SerializeObject(new { tlSn = tlSn, alarmTypeKey = alarmTypeKey, paramList = paramList, houseSn, wellSn }); string rsString = callWebService(url, body); if (string.IsNullOrEmpty(rsString)) return; var result = JsonConvert.DeserializeObject(rsString); if (!result.success) { ErrorLog($"{funcName}服务器返回失败:{rsString}", LogEnum.RunError); return; } return; } catch (Exception ex) { ExLog(ex, "Login"); return; } } public void AlarmApi1(string tlSn, string alarmTypeKey, List paramList) { string funcName = "AlarmApi1"; try { string url = "/api/tl/control/alarm/reportCloudAlarm"; string body = JsonConvert.SerializeObject(new { tlSn = tlSn, alarmTypeKey = alarmTypeKey, paramList = paramList, }); string rsString = callWebService(url, body); if (string.IsNullOrEmpty(rsString)) return; var result = JsonConvert.DeserializeObject(rsString); if (!result.success) { ErrorLog($"{funcName}服务器返回失败:{rsString}", LogEnum.RunError); return; } return; } catch (Exception ex) { ExLog(ex, "Login"); return; } } #region 基础操作 public UserInfo Login(string _account, string _passWord) { string funcName = "Login"; try { account = _account; passWord = _passWord; string json = callWebServiceNoToken("/api/gateway/auth/login", JsonConvert.SerializeObject(new { account = account, password = passWord })); if (string.IsNullOrEmpty(json)) return null; var result = JsonConvert.DeserializeObject>(json); if (!result.success) { ErrorLog($"{funcName}服务器返回失败:{json}", LogEnum.RunError); token = null; return null; } if (result.data != null) { token = result.data.token; return result.data.userInfo; } ErrorLog($"{funcName}接口返回成功但是无数据 {json}", LogEnum.RunError); token = null; return null; } catch (Exception ex) { ExLog(ex, "Login"); token = null; return null; } } public string GetToken() { string funcName = "GetToken"; try { if (!string.IsNullOrEmpty(token)) return token; string json = callWebServiceNoToken("/api/gateway/auth/login", JsonConvert.SerializeObject(new { account = account, password = passWord })); if (string.IsNullOrEmpty(json)) return null; var result = JsonConvert.DeserializeObject>(json); if (!result.success) { ErrorLog($"{funcName}服务器返回失败:{json}", LogEnum.RunError); token = null; return null; } if (result.data != null) { token = result.data.token; return token; } ErrorLog($"{funcName}返回成功但是无数据 {json}", LogEnum.RunError); token = null; return token; } catch (Exception ex) { ExLog(ex, funcName); token = null; return null; } } public string callWebService(string url) { try { if (string.IsNullOrEmpty(GetToken())) return null; using var requestNew = new HttpRequestMessage(HttpMethod.Post, url); requestNew.Headers.Add("token", token); return HttpClientSendAsync(requestNew, url).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { ExceptionLogEvent?.Invoke(ex, $"访问服务器异常:[url:{url}]", null, LogEnum.RunException); return null; } } public string callWebService(string url, string body) { try { if (string.IsNullOrEmpty(GetToken())) return null; using var requestNew = new HttpRequestMessage(HttpMethod.Post, url); using HttpContent httpContent1 = new StringContent(body, Encoding.UTF8, "application/json"); requestNew.Content = httpContent1; requestNew.Headers.Add("token", token); return HttpClientSendAsync(requestNew, url).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { ExceptionLogEvent?.Invoke(ex, $"访问服务器异常:[url:{url}],body:{body}", null, LogEnum.RunException); return null; } } public string callWebServiceSteam(string url, string body) { try { if (string.IsNullOrEmpty(GetToken())) return null; using var requestNew = new HttpRequestMessage(HttpMethod.Post, url); using HttpContent httpContent1 = new StringContent(body, Encoding.UTF8, "application/json"); requestNew.Content = httpContent1; requestNew.Headers.Add("token", token); return HttpClientSendAsyncStream(requestNew, url).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { ExceptionLogEvent?.Invoke(ex, $"访问服务器异常:[url:{url}],body:{body}", null, LogEnum.RunException); return null; } } public string callWebService(string url, Dictionary body) { try { if (string.IsNullOrEmpty(GetToken())) return null; using var requestNew = new HttpRequestMessage(HttpMethod.Post, url); using HttpContent httpContent1 = new FormUrlEncodedContent(body); requestNew.Content = httpContent1; requestNew.Headers.Add("token", token); return HttpClientSendAsync(requestNew, url).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { ExceptionLogEvent?.Invoke(ex, $"访问服务器异常:[url:{url}],body:{JsonConvert.SerializeObject(body)}", null, LogEnum.RunException); return null; } } public string callWebServiceNoToken(string url, string body) { try { using var requestNew = new HttpRequestMessage(HttpMethod.Post, url); using HttpContent httpContent1 = new StringContent(body, Encoding.UTF8, "application/json"); requestNew.Content = httpContent1; return HttpClientSendAsync(requestNew, url).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { ExceptionLogEvent?.Invoke(ex, $"访问服务器异常:[url:{url}],body:{body}", null, LogEnum.RunException); return null; } } public async Task HttpClientSendAsync(HttpRequestMessage request, string url) { string traceId = Guid.NewGuid().ToString("N"); using var cts = new CancellationTokenSource(AsyncTimeout); try { request.Headers.Add("traceId", traceId); using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { ErrorLogEvent?.Invoke($"HttpClientSendAsync访问服务器失败 [url:{url}],[TraceID:{traceId}][code:{response.StatusCode}]", LogEnum.RunError); return null; } return response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult(); } catch (TaskCanceledException ex) when (cts.IsCancellationRequested) { ErrorLogEvent?.Invoke($"HttpClientSendAsync请求超时 [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return null; } catch (HttpRequestException ex) { ExceptionLogEvent?.Invoke(ex, $"HttpClientSendAsync网络异常 [url:{url}],[TraceID:{traceId}]", null, LogEnum.RunException); return null; } catch (Exception ex) { ExceptionLogEvent?.Invoke(ex, $"HttpClientSendAsync访问服务器异常:[url:{url}],[traceId:{traceId}],", null, LogEnum.RunException); return null; } } public async Task HttpClientSendAsyncStream(HttpRequestMessage request, string url) { string result = string.Empty; string traceId = Guid.NewGuid().ToString("N"); using var cts = new CancellationTokenSource(AsyncTimeout); try { request.Headers.Add("traceId", traceId); using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { ErrorLogEvent?.Invoke($"HttpClientSendAsyncStream访问服务器失败 [url:{url}],[TraceID:{traceId}][code:{response.StatusCode}]", LogEnum.RunError); return null; } var buffer = new char[4096]; int bytesRead; var StringBuilderResult = new StringBuilder(); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { using (var reader = new StreamReader(stream, Encoding.UTF8)) { while ((bytesRead = await reader.ReadAsync(buffer).ConfigureAwait(false)) > 0) { StringBuilderResult.Append(buffer, 0, bytesRead); } } } result = StringBuilderResult.ToString(); StringBuilderResult.Clear(); return result; } catch (TaskCanceledException ex) when (cts.IsCancellationRequested) { ErrorLogEvent?.Invoke($"HttpClientSendAsyncStream请求超时 [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return null; } catch (HttpRequestException ex) { ExceptionLogEvent?.Invoke(ex, $"HttpClientSendAsyncStream网络异常 [url:{url}],[TraceID:{traceId}]", null, LogEnum.RunException); return null; } catch (Exception ex) { ExceptionLogEvent?.Invoke(ex, $"HttpClientSendAsyncStream访问服务器异常:[url:{url}],[traceId:{traceId}],", null, LogEnum.RunException); return null; } } #endregion } }