using Container.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net; using System.Web; using System.Windows; namespace Container.Common { public class MyHttpClient { private static App app = ((App)Application.Current); private static Class_Log Mylog = new Class_Log(); private static void init_Request(ref HttpWebRequest request) { request.Accept = "text/json,*/*;q=0.5"; request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7"); request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9"); request.AutomaticDecompression = DecompressionMethods.GZip; request.Timeout = 60000; } public static string Get(string url) { try { var request = (HttpWebRequest)WebRequest.Create(url); { string retval; init_Request(ref request); using (var response = request.GetResponse()) { using (var reader = new System.IO.StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException(), System.Text.Encoding.UTF8)) { retval = reader.ReadToEnd(); } } return retval; } } catch { // ignored } return null; } //判断链接可用 public static bool IsCanConnect(string url, int timeout = 1000) { HttpWebRequest req = null; HttpWebResponse res = null; bool CanCn = true; try { req = (HttpWebRequest)WebRequest.Create(url); req.Method = "HEAD"; req.Timeout = timeout; res = (HttpWebResponse)req.GetResponse(); CanCn = res.StatusCode.ToString() == "OK"; } catch (Exception ex) { CanCn = false; //无法连接 } finally { if (res != null) { res.Close(); } } return CanCn; } public static string Post(string url, string data, string contentType = "application/x-www-form-urlencoded; charset=utf-8", Dictionary headers = null) { try { var request = (HttpWebRequest)WebRequest.Create(url); { string retval; init_Request(ref request); request.Method = "POST"; //request.Timeout = 5000; request.ContentType = contentType; if (headers != null && headers.Count > 0) { foreach (var h in headers) { request.Headers.Add(h.Key, h.Value); } } var bytes = System.Text.Encoding.UTF8.GetBytes(data); request.ContentLength = bytes.Length; using (var stream = request.GetRequestStream()) { stream.Write(bytes, 0, bytes.Length); } using (var response = request.GetResponse()) { using (var reader = new System.IO.StreamReader(response.GetResponseStream() ?? throw new InvalidOperationException())) { retval = reader.ReadToEnd(); } if (!app.isCheckServerTime) { Class_Log log = new Class_Log(); string[] dates = response.Headers.GetValues("Date"); if (dates.Length > 0) { app.isCheckServerTime = true; string serverTime = GMT2Local(dates[0]).ToString(); log.WriteLogFile(serverTime, "date"); WebSocketManageForLive.SetLocalTimeByStr(serverTime); } } } return retval; } } catch (WebException ex) { var lo = ex.Response.Headers["Location"]; if (!string.IsNullOrEmpty(lo)) return lo; return "request error:" + ex.Message; } } /// /// GMT时间转成本地时间 /// /// 字符串形式的GMT时间 /// public static DateTime GMT2Local(string gmt) { DateTime dt = DateTime.MinValue; try { string pattern = ""; if (gmt.IndexOf("+0") != -1) { gmt = gmt.Replace("GMT", ""); pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz"; } if (gmt.ToUpper().IndexOf("GMT") != -1) { pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; } if (pattern != "") { dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); dt = dt.ToLocalTime(); } else { dt = Convert.ToDateTime(gmt); } } catch (Exception ex) { Class_Log log = new Class_Log(); log.WriteLogFile(ex.ToString(), "Temp113"); } return dt; } /// /// 请求云端方法,带加解密 /// /// /// /// public static string CryptPost(string method, object data, string httpurl = "") { string _result = string.Empty; if (!app.IsCanConnect) { return _result; } try { var timeStamp = CommonLib.CurrentTime(); if (string.IsNullOrEmpty(httpurl)) { httpurl = app.HttpUrl; } var token = SecurityHelper.AesEncrypt(method + timeStamp); string postUrl = string.Concat(httpurl, method, "?token=", HttpUtility.UrlEncode(token), "&time=", timeStamp); string contentType = "application/json; charset=utf-8"; string body = SecurityHelper.AesEncrypt(JsonConvert.SerializeObject(data)); _result = Post(postUrl, body, contentType); _result = SecurityHelper.AesDecrypt(_result); //var Jo = JObject.Parse(res); //string code = Jo.Value("code"); //if (code == ResultCode.Success) //{ // _result.Code = code; // _result.Msg = Jo.Value("msg"); // _result.Data = Jo.Value("data").ToObject(); //} //else //{ // _result.Code = code; // _result.Msg = Jo.Value("msg"); //} } catch (Exception ex) { Mylog.WriteLogFile("请求错误" + ex.ToString(), "MyHttpClientError"); } return _result; } } }