using System; using System.IO; using System.Net.Http.Headers; using System.Net.Http; using System.Net; using System.Text; using Newtonsoft.Json; using ivf_tl_Entity.Entity; using ivf_tl_Entity.Entity.Result; using ivf_tl_Entity.Enums; using System.Windows.Markup; using System.Security.Policy; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using log4net.Layout; using ivf_tl_Entity.ControlEntity; using System.Collections.ObjectModel; using System.Threading.Tasks; using System.Linq; using System.Threading; using System.Web; namespace ivf_tl_Service { public class HttpServiceCall { private static string mUrl = ""; private static string token = ""; private string Account { get; set; } = "admin"; private string PassWord { get; set; } = "123456"; private HttpClient HttpClient { get; set; } private LogService LogService { get; set; } //����߳�ʱ private TimeSpan AsyncTimeout = new TimeSpan(0, 0, 10); //��������ʱ TimeSpan ServiceTimeout = new TimeSpan(0, 0, 12); public HttpServiceCall(string baseUrl, LogService _LogService) { mUrl = baseUrl; LogService = _LogService; #if DEBUG AsyncTimeout = new TimeSpan(0, 30, 0); ServiceTimeout = new TimeSpan(0, 30, 0); #endif HttpClient = new HttpClient() { BaseAddress = new Uri(mUrl), Timeout = ServiceTimeout }; HttpClient.DefaultRequestHeaders.ExpectContinue = false; System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; } public string UrlEncode(string url) { try { return url.Replace("+", "%2B").Replace(",", "%2C"); url = url.Replace("+", "%2B").Replace(" ", "%20"); return HttpUtility.UrlEncode(url); } catch (Exception ex) { LogService.ExceptionLog(ex, $"����url·����[url:{url}]", LogEnum.RunException); return url; } } public UserInfo Login(string account, string pass) { string funcName = "HttpServiceCall.Login"; try { Account = account; PassWord = pass; string json = callWebServiceNoToken("/api/gateway/auth/login", JsonConvert.SerializeObject(new { account = Account, password = PassWord })); if (string.IsNullOrEmpty(json)) { token = null; return null; } var result = JsonConvert.DeserializeObject>(json); if (!result.success) { LogService.TLLog($"{funcName}����������ʧ�ܣ�{json}", LogEnum.RunError); token = null; return null; } if (result.data != null) { token = result.data.token; return result.data.userInfo; } LogService.TLLog($"{funcName}���سɹ�������û�����ݣ�{json}", LogEnum.RunError); token = null; return null; } catch (Exception ex) { LogService.ExceptionLog(ex, $"GetToken�쳣", LogEnum.RunException); token = null; return null; } } public string GetToken() { string funcName = "HttpServiceCall.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) { LogService.TLLog($"{funcName}�ӿڷ���ʧ�� {json}", LogEnum.RunError); token = null; return null; } if (result.data != null) { token = result.data.token; return token; } LogService.TLLog($"{funcName}���سɹ����������� {json}", LogEnum.RunError); token = null; return token; } catch (Exception ex) { LogService.ExceptionLog(ex, funcName, LogEnum.RunException); token = null; return null; } } /// /// �����ֵ�Type��ѯ - �������ڵ� /// /// public List QueryDictionaryByTypeApi(string queryType) { string funcName = "HttpServiceCall.QueryDictionaryByTypeApi"; try { string url = "/api/businessManage/pc/dictionary/queryDictionaryByType"; string resultString = callWebService(url, JsonConvert.SerializeObject(new { type = queryType })); if (string.IsNullOrEmpty(resultString)) return new List(); ResultEntity> rs = JsonConvert.DeserializeObject>>(resultString); if (!rs.success) { LogService.TLLog($"{funcName}�ӿڷ���ʧ�� {resultString}", LogEnum.RunError); return new List(); } if (rs.data != null) return rs.data; //LogService.TLLog($"{funcName}���سɹ����������� {resultString}", LogEnum.RunError); return new List(); } catch (Exception ex) { LogService.ExceptionLog(ex, funcName, LogEnum.RunException); return new List(); } } public string UpdatePasswordApi(string password, string newPassword, string verifyPassword) { string funcName = "UpdatePasswordApi"; try { string url = "/api/gateway/auth/user/updatePassword"; string resultString = callWebService(url, JsonConvert.SerializeObject(new { password, newPassword, verifyPassword })); if (string.IsNullOrEmpty(resultString)) return "���������ؿ�"; var rs = JsonConvert.DeserializeObject(resultString); if (!rs.success) { LogService.TLLog($"{funcName}�ӿڷ���ʧ�� {resultString}", LogEnum.RunError); return rs.message; } return null; } catch (Exception ex) { LogService.ExceptionLog(ex, funcName, LogEnum.RunException); return ex.Message; } } public List GetEnvironmentTemperatureApi() { string funcName = "GetEnvironmentTemperatureApi"; try { string url = "/api/tl/control/tlInfo/getEnvironmentTemperature"; string resultString = callWebService(url); if (string.IsNullOrEmpty(resultString)) return new List(); var rs = JsonConvert.DeserializeObject>>(resultString); if (!rs.success) { LogService.TLLog($"{funcName}�ӿڷ���ʧ�� {resultString}", LogEnum.RunError); return new List(); } if (rs.data != null && rs.data.Any()) return rs.data; //LogService.TLLog($"{funcName}�ӿڷ��سɹ����������� {resultString}", LogEnum.RunError); return new List(); } catch (Exception ex) { LogService.ExceptionLog(ex, funcName, LogEnum.RunException); return new List(); } } public string GetDownLoadFileName(string url) { if (string.IsNullOrEmpty(GetToken())) return null; string traceId = Guid.NewGuid().ToString("N"); url = UrlEncode(url); using var cts = new CancellationTokenSource(AsyncTimeout); using var request = new HttpRequestMessage(HttpMethod.Get, url); try { request.Headers.Add("token", token); request.Headers.Add("traceId", traceId); using var responseMessage = HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token).Result; if (!responseMessage.IsSuccessStatusCode) { LogService.TLLog($"GetDownLoadFileName���ʷ�����ʧ��", LogEnum.RunError); return null; } if (responseMessage.Content.Headers.ContentDisposition == null) return null; ContentDispositionHeaderValue contentDisposition = responseMessage.Content.Headers.ContentDisposition; string fileName = null; if (!string.IsNullOrEmpty(contentDisposition.FileNameStar)) { fileName = contentDisposition.FileNameStar; } if (!string.IsNullOrEmpty(contentDisposition.FileName)) { fileName = contentDisposition.FileName; } if (!string.IsNullOrEmpty(fileName)) { return fileName.Trim('\"'); } return null; } catch (TaskCanceledException ex) when (cts.IsCancellationRequested) { LogService.TLLog($"����ʱ [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return null; } catch (HttpRequestException ex) { LogService.TLLog($"�����쳣 [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return null; } catch (Exception ex) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:{url}],[traceId:{traceId}],", LogEnum.RunException); return null; } } public async Task DownLoadFileAsync(string url, string newFileName) { try { if (string.IsNullOrEmpty(GetToken())) return 0; url = UrlEncode(url); using var requestNew = new HttpRequestMessage(HttpMethod.Get, url); requestNew.Headers.Add("token", token); return await HttpClientDownLoad(requestNew, url, newFileName).ConfigureAwait(false); } catch (Exception ex) { LogService.ExceptionLog(ex, $"�����ļ��쳣��[url:{url}]", LogEnum.RunException); return -1; } } public async Task DownLoadFileAsync(string url, string newFileName, string body) { try { if (string.IsNullOrEmpty(GetToken())) return 0; url = UrlEncode(url); using var requestNew = new HttpRequestMessage(HttpMethod.Get, url); using HttpContent httpContent1 = new StringContent(body, Encoding.UTF8, "application/json"); requestNew.Content = httpContent1; requestNew.Headers.Add("token", token); return await HttpClientDownLoad(requestNew, url, newFileName).ConfigureAwait(false); } catch (Exception ex) { LogService.ExceptionLog(ex, $"�����ļ��쳣��[url:{url}]", LogEnum.RunException); return -1; } } public byte[] GetImageByteApi(string imageUrl) { try { if (string.IsNullOrEmpty(GetToken())) return null; imageUrl = UrlEncode(imageUrl); using var requestNew = new HttpRequestMessage(HttpMethod.Get, imageUrl); requestNew.Headers.Add("token", token); return HttpClientByte(requestNew, imageUrl).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { LogService.ExceptionLog(ex, $"��ȡͼƬ�����쳣��[url:{imageUrl}]", LogEnum.RunException); 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) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:{url}]", LogEnum.RunException); return null; } } public string callWebService(string url, bool b) { try { if (string.IsNullOrEmpty(GetToken())) return null; using var requestNew = new HttpRequestMessage(HttpMethod.Post, url); using HttpContent httpContent1 = new StringContent("", Encoding.UTF8, "application/x-www-form-urlencoded"); requestNew.Content = httpContent1; requestNew.Headers.Add("token", token); return HttpClientSendAsync(requestNew, url).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (Exception ex) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:{url}]", 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) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:{url}],body��{body}", 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) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:{url}],body��{JsonConvert.SerializeObject(body)}", LogEnum.RunException); return null; } } public string callWebServiceUpLoad(string url, Dictionary body, byte[] fileBtye, string fileName) { try { fileName = HttpUtility.UrlEncode(fileName); if (string.IsNullOrEmpty(GetToken())) return null; using var requestNew = new HttpRequestMessage(HttpMethod.Post, url); using (var content = new MultipartFormDataContent()) { // ���ӱ����ֶ� if (body.Any()) { foreach (var item in body) { content.Add(new StringContent(item.Value), item.Key); } } // �����ļ����� var fileContent = new ByteArrayContent(fileBtye); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "reportHospitalLogoFile", FileName = fileName }; //FileName = HttpUtility.UrlEncode(fileName) content.Add(fileContent); requestNew.Content = content; requestNew.Headers.Add("token", token); return HttpClientSendAsync(requestNew, url).ConfigureAwait(false).GetAwaiter().GetResult(); } } catch (Exception ex) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:{url}],body��{JsonConvert.SerializeObject(body)}", 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) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:{url}],body��{body}", LogEnum.RunException); return null; } } /// /// ����ʵ�� /// /// /// /// public async Task HttpClientSendAsync(HttpRequestMessage request, string url) { // C5:traceId 改取 OperationLogContext(与 operate/Java 链路串联);缺则新建。header 名 "traceId" 与后端一致。 string traceId = Aivfo.OperationLog.OperationLogContext.TraceId ?? Aivfo.OperationLog.OperationLogContext.NewTraceId(); string result; var _opSw = System.Diagnostics.Stopwatch.StartNew(); using var cts = new CancellationTokenSource(AsyncTimeout); try { request.Headers.Add("traceId", traceId); using var response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { LogService.TLLog($"HttpClientSendAsync���ʷ�����ʧ�� [url:{url}],[TraceID:{traceId}][code:{response.StatusCode}]", LogEnum.RunError); _opSw.Stop(); try { Aivfo.OperationLog.OperationLogger.Log("HTTP", url, input: null, result: "失败", error: $"HTTP {(int)response.StatusCode}", elapsedMs: _opSw.ElapsedMilliseconds); } catch { } return null; } _opSw.Stop(); try { Aivfo.OperationLog.OperationLogger.Log("HTTP", url, input: null, result: "成功", elapsedMs: _opSw.ElapsedMilliseconds); } catch { } return response.Content.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult(); } catch (TaskCanceledException ex) when (cts.IsCancellationRequested) { LogService.TLLog($"HttpClientSendAsync����ʱ [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); _opSw.Stop(); try { Aivfo.OperationLog.OperationLogger.Log("HTTP", url, input: null, result: "失败", error: "Timeout", elapsedMs: _opSw.ElapsedMilliseconds); } catch { } return null; } catch (HttpRequestException ex) { LogService.ExceptionLog(ex, $"HttpClientSendAsync�����쳣 [url:{url}],[TraceID:{traceId}]", LogEnum.RunException); _opSw.Stop(); try { Aivfo.OperationLog.OperationLogger.Log("HTTP", url, input: null, result: "失败", error: ex.GetType().Name + ": " + ex.Message, elapsedMs: _opSw.ElapsedMilliseconds); } catch { } return null; } catch (Exception ex) { LogService.ExceptionLog(ex, $"HttpClientSendAsync���ʷ������쳣��[url:{url}],[traceId:{traceId}],", LogEnum.RunException); _opSw.Stop(); try { Aivfo.OperationLog.OperationLogger.Log("HTTP", url, input: null, result: "失败", error: ex.GetType().Name + ": " + ex.Message, elapsedMs: _opSw.ElapsedMilliseconds); } catch { } 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 HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { LogService.TLLog($"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) { LogService.TLLog($"HttpClientSendAsyncStream����ʱ [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return null; } catch (HttpRequestException ex) { LogService.ExceptionLog(ex, $"HttpClientSendAsyncStream�����쳣 [url:{url}],[TraceID:{traceId}]", LogEnum.RunException); return null; } catch (Exception ex) { LogService.ExceptionLog(ex, $"HttpClientSendAsyncStream���ʷ������쳣��[url:{url}],[traceId:{traceId}],", LogEnum.RunException); return null; } } public async Task HttpClientByte(HttpRequestMessage request, string url) { string traceId = Guid.NewGuid().ToString("N"); string result; using var cts = new CancellationTokenSource(AsyncTimeout); try { request.Headers.Add("traceId", traceId); using var response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { LogService.TLLog($"HttpClientByte���ʷ�����ʧ�� [url:{url}],[TraceID:{traceId}][code:{response.StatusCode}]", LogEnum.RunError); return null; } return response.Content.ReadAsByteArrayAsync().ConfigureAwait(false).GetAwaiter().GetResult(); } catch (TaskCanceledException ex) when (cts.IsCancellationRequested) { LogService.TLLog($"HttpClientByte����ʱ [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return null; } catch (HttpRequestException ex) { LogService.TLLog($"HttpClientByte�����쳣 [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return null; } catch (Exception ex) { LogService.ExceptionLog(ex, $"HttpClientByte���ʷ������쳣��[url:{url}],[traceId:{traceId}],", LogEnum.RunException); return null; } } public async Task HttpClientDownLoad(HttpRequestMessage request, string url, string newFileName) { string traceId = Guid.NewGuid().ToString("N"); using var cts = new CancellationTokenSource(AsyncTimeout); try { request.Headers.Add("traceId", traceId); using var response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { LogService.TLLog($"HttpClientDownLoad���ʷ�����ʧ�� [url:{url}],[TraceID:{traceId}][code:{response.StatusCode}]", LogEnum.RunError); return 0; } using (var fs = File.Create(newFileName)) { using (var download = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { var buffer = new byte[4096]; int bytesRead; while ((bytesRead = download.Read(buffer)) > 0) { await fs.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false); } } } return 1; } catch (TaskCanceledException ex) when (cts.IsCancellationRequested) { LogService.TLLog($"HttpClientDownLoad����ʱ [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return -1; } catch (HttpRequestException ex) { LogService.TLLog($"HttpClientDownLoad�����쳣 [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return -1; } catch (Exception ex) { LogService.ExceptionLog(ex, $"HttpClientDownLoad���ʷ������쳣��[url:{url}],[traceId:{traceId}],", LogEnum.RunException); return -1; } } #region public bool callWebService(string url, string body, string newFilePath) { string traceId = Guid.NewGuid().ToString("N"); try { if (string.IsNullOrEmpty(GetToken())) return false; HttpContent httpContent = new StringContent(body); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); httpContent.Headers.ContentType.CharSet = "utf-8"; CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(AsyncTimeout); var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = httpContent }; request.Headers.Add("token", token); request.Headers.Add("traceId", traceId); HttpResponseMessage responseMessage = HttpClient.SendAsync(request, cancellationTokenSource.Token).Result; if (responseMessage.StatusCode != HttpStatusCode.OK) { LogService.TLLog($"���ʷ�����ʧ�ܣ�[url:{url}],[traceId:{traceId}],{body}", LogEnum.RunError); return false; } var resultStream = responseMessage.Content.ReadAsStreamAsync().Result; if (resultStream == null) { LogService.TLLog($"���������ؿգ�[url:{url}],[traceId:{traceId}],{body}", LogEnum.RunError); return false; } using (var fs = File.Create(newFilePath)) { resultStream.CopyTo(fs); fs.Close(); } return true; } catch (Exception ex) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:{url}],[traceId:{traceId}],{body}", LogEnum.RunException); return false; } } public async Task GetImageByteApi1(string imageUrl) { HttpResponseMessage responseMessage = null; string traceId = Guid.NewGuid().ToString("N"); try { imageUrl = imageUrl.Replace("+", "%2B"); imageUrl = imageUrl.Replace(",", "%2C"); if (string.IsNullOrEmpty(GetToken())) return null; var request = new HttpRequestMessage(HttpMethod.Get, imageUrl); request.Headers.Add("token", token); request.Headers.Add("traceId", traceId); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.CancelAfter(10000); using (responseMessage = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationTokenSource.Token).ConfigureAwait(false)) { if (responseMessage.StatusCode != HttpStatusCode.OK) { LogService.TLLog($"GetImageByteApi���ʷ�����ʧ�ܣ�[url:{imageUrl}],[traceId:{traceId}]", LogEnum.RunError); return null; } return await responseMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false); } } catch (Exception ex) { LogService.ExceptionLog(ex, $"���ʷ������쳣��[url:GetImageByteApi:{imageUrl}],[traceId:{traceId}]", LogEnum.RunException); return null; } } #endregion } }