Files
1440WGJ/JY.MES/MESApiHelper.cs
T

83 lines
2.8 KiB
C#
Raw Normal View History

2026-07-14 13:55:17 +08:00
using JY.MES.Entity;
2026-07-14 16:09:25 +08:00
using JY.MES.Enum;
using JY.MES.Exceptions;
using JY.MES.MES;
2026-07-14 13:55:17 +08:00
using Newtonsoft.Json;
using System;
2026-07-14 16:09:25 +08:00
using System.CodeDom;
2026-07-14 13:55:17 +08:00
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
{
/// <summary>
/// MES接口类
/// </summary>
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)
{
2026-07-14 16:09:25 +08:00
throw new MesNetworkException($"massage:[{ex.InnerException}],mes: [MES反馈超时或无法访间MES服务器]");
2026-07-14 13:55:17 +08:00
}
}
2026-07-14 16:09:25 +08:00
public static MesCallResult<T> HttpPostJsonAPI<T>(string url, string strJosnData, double MesRequestTime)
{
var result = new MesCallResult<T>() { 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<T>(respJsonStr);
result.IsSuccess = true;
result.OriResponse = mesResp;
result.OriRespJsonStr = respJsonStr;
}
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;
}
return result;
}
2026-07-14 13:55:17 +08:00
}
}