using JY.MES.Entity; using JY.MES.Enum; using JY.MES.Exceptions; using JY.MES.MES; using Newtonsoft.Json; using System; using System.CodeDom; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.Serialization.Json; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; namespace JY.MES { /// /// MES接口类 /// public class MESApiHelper { public static string HttpPostJsonAPI(string url, string strJosnData, double MesRequestTime) { MesResponse mesResponse = new MesResponse(); try { StringContent stringContent = new StringContent(strJosnData, Encoding.UTF8, "application/json"); return new HttpClient() { Timeout = TimeSpan.FromSeconds(MesRequestTime) }.PostAsync(url, (HttpContent)stringContent).Result.Content.ReadAsStringAsync().Result; } catch (Exception ex) { throw new MesNetworkException($"massage:[{ex.InnerException}],mes: [MES反馈超时或无法访间MES服务器]"); } } public static MesCallResult HttpPostJsonAPI(string url, string strJosnData, double MesRequestTime) { var result = new MesCallResult() { IsSuccess = false }; try { StringContent stringContent = new StringContent(strJosnData, Encoding.UTF8, "application/json"); string respJsonStr = new HttpClient() { Timeout = TimeSpan.FromSeconds(MesRequestTime) }.PostAsync(url, (HttpContent)stringContent).Result.Content.ReadAsStringAsync().Result; var mesResp = JsonConvert.DeserializeObject(respJsonStr); result.IsSuccess = true; result.OriResponse = mesResp; result.OriRespJsonStr = respJsonStr; } catch (TaskCanceledException ex) { result.ErrorType = MesErrorType.NetworkTimeout; result.ErrorMessage = $"MES请求超时: {ex.Message}"; return result; } catch (TimeoutException ex) { result.ErrorType = MesErrorType.NetworkTimeout; result.ErrorMessage = $"MES请求超时: {ex.Message}"; return result; } catch (HttpRequestException ex) { result.ErrorType = MesErrorType.NetworkError; result.ErrorMessage = $"MES网络请求失败: {ex.Message}"; return result; } catch (JsonException ex) { result.ErrorType = MesErrorType.ParseError; result.ErrorMessage = $"MES响应解析失败: {ex.Message}"; return result; } catch (Exception ex) { result.ErrorType = MesErrorType.NetworkTimeout; result.ErrorMessage = $"MES请求超时: {ex.Message}"; return result; } return result; } } }