using JinYuan.MES.Models; using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; namespace JinYuan.MES { /// /// MES接口类 /// public class MESApiHelper { static HttpClient httpClient; private static readonly Lazy _httpClient = new Lazy(() => new HttpClient()); public static HttpClient Instance => _httpClient.Value; public MESApiHelper() { } public static string WepPostAPIAsync(string url, string strJosnData) { MesResponse mesResponse = new MesResponse(); try { StringContent stringContent = new StringContent(strJosnData, Encoding.UTF8, "application/json"); string ResponseMessage = new HttpClient() { Timeout = TimeSpan.FromSeconds(3.0) }.PostAsync(url, (HttpContent)stringContent).Result.Content.ReadAsStringAsync().Result; return ResponseMessage; } catch (Exception ex) { mesResponse.success = false; mesResponse.message = ex.Message; return JsonConvert.SerializeObject(mesResponse); } } public static string HttpPostJsonAPI(string url, string strJosnData) { MesResponse mesResponse = new MesResponse(); try { StringContent stringContent = new StringContent(strJosnData, Encoding.UTF8, "application/json"); return new HttpClient() { Timeout = TimeSpan.FromSeconds(5.0) }.PostAsync(url, (HttpContent)stringContent).Result.Content.ReadAsStringAsync().Result; } catch (Exception ex) { mesResponse.success = false; mesResponse.message = ex.Message; return JsonConvert.SerializeObject(mesResponse); } } /// /// /// /// /// /// public string WebApiPost(string url, string strJosnData) { MesResponse mesResponse = new MesResponse(); try { HttpContent stringContent = new StringContent(strJosnData); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var _response = httpClient.PostAsync(url, stringContent).Result; var _clientResult = _response.Content.ReadAsStringAsync().Result; return _clientResult; } catch (Exception ex) { mesResponse.code = "99"; mesResponse.success = false; mesResponse.message = ex.Message; return JsonConvert.SerializeObject(mesResponse); } } /// /// 同步上传 /// /// /// /// public static string WebApiPostTranafer(string url, string json) { try { byte[] bytes = Encoding.UTF8.GetBytes(json); WebClient client = new WebClient(); client.Headers.Add("Content-type", "application/json"); client.Headers.Add("ContentLength", json.Length.ToString()); Encoding enc = Encoding.GetEncoding("UTF-8"); byte[] responsedata = client.UploadData(url, "Post", bytes); string res = enc.GetString(responsedata); return res; } catch (System.Exception ex) { return null; } } } }