using Lskj.Web.Core.Util; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace Lskj.Util { public static class HttpHelper { private const int RequestTimeout = 120000; private const int Tls12 = 3072; private const int UploadChunkMaxAttempts = 3; public enum Encode { Default = 0, UTF8 = 1 } private static string ContentType = string.Empty;// "application/x-www-form-urlencoded"; private static string Accept = string.Empty;//"text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; private static string UserAgent = string.Empty;//"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"; private static Encode EncodeMode = Encode.Default; public static void Setting(string contentType, string accept, string userAgent, Encode encode = Encode.Default) { ContentType = contentType; Accept = accept; UserAgent = userAgent; EncodeMode = encode; } private static void ConfigureTransport() { try { ServicePointManager.SecurityProtocol |= (SecurityProtocolType)Tls12; ServicePointManager.Expect100Continue = false; if (ServicePointManager.DefaultConnectionLimit < 20) { ServicePointManager.DefaultConnectionLimit = 20; } } catch { } } private static void ConfigureRequest(HttpWebRequest request) { request.Timeout = RequestTimeout; request.ReadWriteTimeout = RequestTimeout; request.KeepAlive = false; request.ServicePoint.Expect100Continue = false; request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } private static string BuildExceptionMessage(Exception ex) { StringBuilder builder = new StringBuilder(); builder.Append(ex.Message); if (ex.InnerException != null) { builder.AppendFormat("; Inner={0}", ex.InnerException.Message); } return builder.ToString(); } private static string BuildWebExceptionMessage(WebException ex) { StringBuilder builder = new StringBuilder(); builder.Append(BuildExceptionMessage(ex)); builder.AppendFormat("; Status={0}", ex.Status); HttpWebResponse response = ex.Response as HttpWebResponse; if (response != null) { builder.AppendFormat("; HttpStatus={0} {1}", (int)response.StatusCode, response.StatusDescription); try { Stream responseStream = response.GetResponseStream(); if (responseStream != null) { using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8)) { string responseText = streamReader.ReadToEnd(); if (!string.IsNullOrEmpty(responseText)) { builder.AppendFormat("; Response={0}", responseText); } } } } catch { } } return builder.ToString(); } private static bool IsTransientUploadException(WebException ex) { if (ex == null) { return false; } switch (ex.Status) { case WebExceptionStatus.ConnectFailure: case WebExceptionStatus.ConnectionClosed: case WebExceptionStatus.KeepAliveFailure: case WebExceptionStatus.PipelineFailure: case WebExceptionStatus.ReceiveFailure: case WebExceptionStatus.SendFailure: case WebExceptionStatus.Timeout: return true; default: return false; } } /// /// post数据到指定的网址,获取cookie数据,和返回页 /// public static HttpWebResponse Post(string url, string postData, Dictionary pmsDic, Dictionary headerDic, out string result) { HttpWebResponse httpWebResponse = null; try { HttpWebRequest httpWebRequest; ConfigureTransport(); httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); ConfigureRequest(httpWebRequest); httpWebRequest.ContentType = ContentType; httpWebRequest.Accept = Accept; httpWebRequest.UserAgent = UserAgent; httpWebRequest.Method = "POST"; byte[] byteRequest = null; if (headerDic != null) { foreach (var item in headerDic) { if (item.Key.Equals("Content-Type")) { httpWebRequest.ContentType = item.Value; } else { httpWebRequest.Headers.Add(item.Key, item.Value); } } } if (!string.IsNullOrEmpty(postData)) { switch (EncodeMode) { case Encode.Default: byteRequest = Encoding.Default.GetBytes(postData); break; case Encode.UTF8: byteRequest = Encoding.UTF8.GetBytes(postData); break; } httpWebRequest.ContentLength = byteRequest.Length; } else if (pmsDic != null) { StringBuilder builder = new StringBuilder(); int i = 0; foreach (var item in pmsDic) { if (i > 0) builder.Append("&"); builder.AppendFormat("{0}={1}", item.Key, item.Value); i++; } switch (EncodeMode) { case Encode.Default: byteRequest = Encoding.Default.GetBytes(builder.ToString()); break; case Encode.UTF8: byteRequest = Encoding.UTF8.GetBytes(builder.ToString()); break; } httpWebRequest.ContentLength = byteRequest.Length; } Stream stream = httpWebRequest.GetRequestStream(); stream.Write(byteRequest, 0, byteRequest.Length); stream.Close(); httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream responseStream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); result = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); return httpWebResponse; } catch (WebException ex) { Console.WriteLine(ex.ToString()); result = BuildWebExceptionMessage(ex); return httpWebResponse; } catch (Exception ex) { Console.WriteLine(ex.ToString()); result = BuildExceptionMessage(ex); return httpWebResponse; } } /// /// Get到指定的网址,获取cookie数据,和返回页 /// public static HttpWebResponse Get(string url, string postData, Dictionary pmsDic, Dictionary headerDic, out string result) { HttpWebResponse httpWebResponse = null; try { StringBuilder builder = new StringBuilder(url); if (pmsDic != null && pmsDic.Count > 0) { builder.Append("?"); int i = 0; foreach (var item in pmsDic) { if (i > 0) builder.Append("&"); builder.AppendFormat("{0}={1}", item.Key, item.Value); i++; } } HttpWebRequest httpWebRequest; ConfigureTransport(); httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(builder.ToString()); ConfigureRequest(httpWebRequest); httpWebRequest.ContentType = ContentType; //httpWebRequest.Referer = url; httpWebRequest.Accept = Accept; httpWebRequest.UserAgent = UserAgent; httpWebRequest.Method = "GET"; if (headerDic != null) { foreach (var item in headerDic) { if (item.Key.Equals("Content-Type")) { httpWebRequest.ContentType = item.Value; } else { httpWebRequest.Headers.Add(item.Key, item.Value); } } } httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream responseStream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); result = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); return httpWebResponse; } catch (WebException ex) { Console.WriteLine(ex.ToString()); result = BuildWebExceptionMessage(ex); return httpWebResponse; } catch (Exception ex) { Console.WriteLine(ex.ToString()); result = BuildExceptionMessage(ex); return httpWebResponse; } } /// /// 分片上传 /// /// /// /// /// /// /// public static HttpWebResponse PostFileChunk(string url, byte[] fileBytes, string fileName, Dictionary headerDic, out string result) { result = ""; for (int attempt = 1; attempt <= UploadChunkMaxAttempts; attempt++) { HttpWebRequest httpWebRequest = null; HttpWebResponse httpWebResponse = null; try { string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x"); ConfigureTransport(); httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); ConfigureRequest(httpWebRequest); // 客户网络中的代理/防火墙可能在复用连接时主动断开。 // 分片请求使用独立连接,避免 ERP 进程内其他 HTTP 请求 // 留下的连接状态影响当前上传。 httpWebRequest.KeepAlive = false; httpWebRequest.ConnectionGroupName = "LserpUpload-" + Guid.NewGuid().ToString("N"); httpWebRequest.ProtocolVersion = HttpVersion.Version11; httpWebRequest.Method = "POST"; httpWebRequest.Accept = Accept; httpWebRequest.UserAgent = string.IsNullOrEmpty(UserAgent) ? "Lserp-Desktop/6.0" : UserAgent; httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; if (headerDic != null) { foreach (var item in headerDic) { if (!item.Key.Equals("Content-Type")) { httpWebRequest.Headers.Add(item.Key, item.Value); } } } string header = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n"; string footer = "\r\n--" + boundary + "--\r\n"; byte[] headerBytes = Encoding.UTF8.GetBytes(header); byte[] footerBytes = Encoding.UTF8.GetBytes(footer); httpWebRequest.ContentLength = headerBytes.Length + fileBytes.Length + footerBytes.Length; using (Stream stream = httpWebRequest.GetRequestStream()) { stream.Write(headerBytes, 0, headerBytes.Length); stream.Write(fileBytes, 0, fileBytes.Length); stream.Write(footerBytes, 0, footerBytes.Length); } httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (Stream responseStream = httpWebResponse.GetResponseStream()) using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8)) { result = streamReader.ReadToEnd(); } return httpWebResponse; } catch (WebException ex) { Console.WriteLine(ex.ToString()); string exceptionMessage = BuildWebExceptionMessage(ex); httpWebResponse?.Close(); ex.Response?.Close(); httpWebRequest?.Abort(); if (attempt < UploadChunkMaxAttempts && IsTransientUploadException(ex)) { System.Threading.Thread.Sleep(attempt * 1000); continue; } result = string.Format("{0}; Attempts={1}", exceptionMessage, attempt); return null; } catch (Exception ex) { Console.WriteLine(ex.ToString()); httpWebResponse?.Close(); httpWebRequest?.Abort(); result = BuildExceptionMessage(ex); return null; } } return null; } /// /// url转换 /// /// /// public static string ToEnUrl(string url) { string[] urlParams = url.Split('?'); string enKey = "encrypt", enVal = ""; bool hasEn = false; if (urlParams.Length > 1) { string[] queryParams = urlParams[1].Split('&'); List qpLS = new List(); Hashtable pms = new Hashtable(); hasEn = queryParams.Any(str => str.Trim().StartsWith(enKey, StringComparison.OrdinalIgnoreCase)); foreach (string q in queryParams) { string[] eqParams = q.Split('='); if (eqParams.Length > 1) { if (hasEn && eqParams[0].ToLower() == enKey) { enVal = eqParams[1]; continue; } if (hasEn || eqParams[0].ToLower() == "username" || eqParams[0].ToLower() == "password") { pms.Add(eqParams[0], eqParams[1]); } else { qpLS.Add(string.Format("{0}={1}", eqParams[0], HttpUtility.UrlEncode(eqParams[1]))); } } else { } } if (pms.Count > 0) { DateTime dateTime = DateTime.Now.AddDays(1); DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); long timestamp = (dateTime.Ticks - epoch.Ticks) / TimeSpan.TicksPerSecond; pms.Add("exp", timestamp); } return $"{urlParams[0]}?pms={HttpUtility.UrlEncode(hasEn ? Lskj.Web.Core.Util.safety.AESUtil.Encrypt(JSON.Encode(pms), enVal) : Lskj.Web.Core.Util.safety.AESUtil.MobileEncrypt(JSON.Encode(pms)))}&{qpLS.SJoin("&")}"; } return url; } } }