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) { 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($"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) { LogService.TLLog($"HttpClientSendAsync请求超时 [url:{url}],[TraceID:{traceId}]", LogEnum.RunError); return null; } catch (HttpRequestException ex) { LogService.ExceptionLog(ex, $"HttpClientSendAsync网络异常 [url:{url}],[TraceID:{traceId}]", LogEnum.RunException); return null; } catch (Exception ex) { LogService.ExceptionLog(ex, $"HttpClientSendAsync访问服务器异常:[url:{url}],[traceId:{traceId}],", 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 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 } }