场景:用于绑定ip在某服务器上,但需要本地调试,此时需再服务器做个中转
一般处理程序ashx:
/// <summary> /// 中转 绑定ip中转请求;参数Base64解密,gzip压缩返回; /// kk /// </summary> public class tc : IHttpHandler { public void ProcessRequest(HttpContext context) { Dictionary<string, string> dict = AnaylerUrlParaGet(context.Request); if (dict.Count == 0 || string.IsNullOrEmpty(dict["url"]) || string.IsNullOrEmpty(dict["postdata"])) { context.Response.ContentType = "text/plain"; context.Response.Write("no post data"); context.Response.End(); } HttpUtil _httputil = new HttpUtil(); string strurl = Base64.DecodeBase64IgnoreEmpty(dict["url"]); string strJson = Base64.DecodeBase64IgnoreEmpty(dict["postdata"]); string strcontext = _httputil.HttpPost(strurl, strJson, System.Text.Encoding.UTF8); context.Response.ContentType = "application/octet-stream"; context.Response.BinaryWrite(Common.EncryptHelper.Compress(strcontext)); context.Response.Flush(); context.Response.End(); } public bool IsReusable { get { return false; } } /// <summary> /// 获取GET参数 /// </summary> /// <param name="req"></param> /// <returns></returns> public Dictionary<string, string> AnaylerUrlParaGet(System.Web.HttpRequest req) { Dictionary<string, string> dict = new Dictionary<string, string>(); string tmp1; string tmp2; System.Collections.Specialized.NameValueCollection col = req.QueryString; for (int i = 0; i < col.Count; i++) { tmp1 = col.AllKeys[i].Trim(); tmp2 = col[i].Trim(); if (!dict.ContainsKey(tmp1)) { dict.Add(tmp1, tmp2); } } return dict; } }
调用:
private string PolicyMethod(object req, string strurl) { string result = string.Empty; try { string BindUrl = "http://http://localhost:3600/tc.ashx"; //服务器对应ip地址 string strdata = GZipUtils.Compress(SerializeUtil.SerializeXml(req), Encoding.Unicode); string url = BindUrl + "?url=" + Base64.EncodeBase64IgnoreEmpty(strurl) + "&postdata=" + Base64.EncodeBase64IgnoreEmpty(strdata); result = _httputil.HttpGet(url, System.Text.Encoding.UTF8, "gzip", 20); } catch (Exception ex) { LogUtils.Debug("PolicyMethod出错:" + ex.Message); } return result; }
HttpUtil帮助类:
public class HttpUtil { public string HttpPost(string url, string data, Encoding encoding) { return HttpPost(url, data, "text/plain", encoding); } public string HttpGet(string url, Encoding encoding) { return HttpSend(url, "", "text/plain", Encoding.GetEncoding("utf-8"), "GET"); } public string HttpGet(string url, Encoding encoding, int timeout) { return HttpSend(url, "", "text/plain", Encoding.GetEncoding("utf-8"), "GET", null, "", timeout); } public string HttpGet(string url, string data, string contenttype, Encoding encoding, Dictionary<string, string> Headers = null, string Strcompress = "", int timeout = 0) { return HttpSend(url, data, contenttype, encoding, "GET", Headers, Strcompress, timeout); } public string HttpGet(string url, Encoding encoding, string Strcompress, int timeout = 0) { return HttpSend(url, "", "text/plain", Encoding.GetEncoding("utf-8"), "GET", null, Strcompress, timeout); } public string HttpGet2(string url, Encoding encoding, string Strcompress, int timeout = 0) { return HttpSend2(url, "", "text/plain", Encoding.GetEncoding("utf-8"), "GET", null, Strcompress, timeout); } public string HttpGet(string url, string contenttype, Encoding encoding) { return HttpSend(url, "", contenttype, Encoding.GetEncoding("utf-8"), "GET"); } public string HttpPost(string url, string data, string contenttype, Encoding encoding, Dictionary<string, string> Headers = null, string Strcompress = "", int timeout = 0) { return HttpSend(url, data, contenttype, encoding, "POST", Headers, Strcompress, timeout); } public string HttpPut(string url, string data, string contenttype, Encoding encoding, Dictionary<string, string> Headers = null) { return HttpSend(url, data, contenttype, encoding, "PUT", Headers); } private string HttpSend(string url, string data, string contenttype, Encoding encoding, string method, Dictionary<string, string> Headers = null, string Strcompress = "" , int timeout = 0) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); if (Strcompress == "gzip") { request.Headers.Add("Accept-Encoding", "gzip"); } if (timeout > 0) { request.Timeout = timeout * 1000; } request.Method = method; if (!string.IsNullOrEmpty(contenttype)) request.ContentType = contenttype; //设置Header信息 if (Headers != null && Headers.Count > 0) { foreach (KeyValuePair<string, string> item in Headers) if (!string.IsNullOrEmpty(item.Key) && !string.IsNullOrEmpty(item.Value)) request.Headers.Add(item.Key, item.Value); } if (data != "") { byte[] bs = encoding.GetBytes(data); request.ContentLength = bs.Length; request.Timeout = 120 * 1000; using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); if (Strcompress == "gzip") stream = new GZipStream(stream, CompressionMode.Decompress); //if (response.ContentEncoding.ToLower().Contains("gzip")) // stream = new GZipStream(stream, CompressionMode.Decompress); //else if (response.ContentEncoding.ToLower().Contains("deflate")) // stream = new DeflateStream(stream, CompressionMode.Decompress); MemoryStream memoryStream = new MemoryStream(); int bufferLength = 1024; byte[] b = new byte[bufferLength]; int actual; while ((actual = stream.Read(b, 0, bufferLength)) > 0) { memoryStream.Write(b, 0, actual); } memoryStream.Position = 0; byte[] bt = memoryStream.ToArray(); //无视编码 //if (encoding == null) //{ string temp = Encoding.Default.GetString(bt, 0, bt.Length); //<meta(.*?)charset([\s]?)=[^>](.*?)> Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"‘]", RegexOptions.IgnoreCase | RegexOptions.Multiline); string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty; charter = charter.Replace("\"", string.Empty).Replace("‘", string.Empty).Replace(";", string.Empty); if (charter.Length > 0) { charter = charter.ToLower().Replace("iso-8859-1", "gbk"); encoding = Encoding.GetEncoding(charter); } else { if (response.CharacterSet != null) { if (response.CharacterSet.ToLower().Trim() == "iso-8859-1") { encoding = Encoding.GetEncoding("gbk"); } else { if (string.IsNullOrEmpty(response.CharacterSet.Trim())) { encoding = Encoding.UTF8; } else { encoding = Encoding.GetEncoding(response.CharacterSet); } } } } //} stream.Close(); stream.Dispose(); response.Close(); return encoding.GetString(bt); } catch (Exception e) { LogUtils.Debug(e.Message); return ""; } } private string HttpSend2(string url, string data, string contenttype, Encoding encoding, string method, Dictionary<string, string> Headers = null, string Strcompress = "" , int timeout = 0) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); if (Strcompress == "gzip") { request.Headers.Add("Accept-Encoding", "gzip"); } if (timeout > 0) { request.Timeout = timeout * 1000; } request.Method = method; if (!string.IsNullOrEmpty(contenttype)) request.ContentType = contenttype; //设置Header信息 if (Headers != null && Headers.Count > 0) { foreach (KeyValuePair<string, string> item in Headers) if (!string.IsNullOrEmpty(item.Key) && !string.IsNullOrEmpty(item.Value)) request.Headers.Add(item.Key, item.Value); } if (data != "") { byte[] bs = encoding.GetBytes(data); request.ContentLength = bs.Length; request.Timeout = 120 * 1000; using (Stream reqStream = request.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); if (Strcompress == "gzip") stream = new GZipStream(stream, CompressionMode.Decompress); //if (response.ContentEncoding.ToLower().Contains("gzip")) // stream = new GZipStream(stream, CompressionMode.Decompress); //else if (response.ContentEncoding.ToLower().Contains("deflate")) // stream = new DeflateStream(stream, CompressionMode.Decompress); //stream = new GZipStream(stream, CompressionMode.Decompress); MemoryStream memoryStream = new MemoryStream(); int bufferLength = 1024; byte[] b = new byte[bufferLength]; int actual; while ((actual = stream.Read(b, 0, bufferLength)) > 0) { memoryStream.Write(b, 0, actual); } memoryStream.Position = 0; byte[] bt = memoryStream.ToArray(); //无视编码 //if (encoding == null) //{ string temp = Encoding.Default.GetString(bt, 0, bt.Length); //<meta(.*?)charset([\s]?)=[^>](.*?)> Match meta = Regex.Match(temp, "<meta([^<]*)charset=([^<]*)[\"‘]", RegexOptions.IgnoreCase | RegexOptions.Multiline); string charter = (meta.Groups.Count > 2) ? meta.Groups[2].Value : string.Empty; charter = charter.Replace("\"", string.Empty).Replace("‘", string.Empty).Replace(";", string.Empty); if (charter.Length > 0) { charter = charter.ToLower().Replace("iso-8859-1", "gbk"); encoding = Encoding.GetEncoding(charter); } else { if (response.CharacterSet.ToLower().Trim() == "iso-8859-1") { encoding = Encoding.GetEncoding("gbk"); } else { if (string.IsNullOrEmpty(response.CharacterSet.Trim())) { encoding = Encoding.UTF8; } else { encoding = Encoding.GetEncoding(response.CharacterSet); } } } //} stream.Close(); stream.Dispose(); response.Close(); return encoding.GetString(bt); } catch (Exception e) { return e.Message; LogUtils.Debug(e.Message); return ""; } } /// <summary> /// 以指定编码通过POST方式发送数据。 /// </summary> /// <param name="Url">url</param> /// <param name="postString">Post数据</param> /// <returns></returns> public string PostString(string Url, string postString, Encoding ed) { var data = ed.GetBytes(postString); var request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var wStream = request.GetRequestStream()) { wStream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var rt = string.Empty; using (var rStream = new StreamReader(response.GetResponseStream(), ed)) { rt = rStream.ReadToEnd(); } response.Close(); return rt; } /// <summary> /// 以utf-8编码通过POST方式发送数据。 /// </summary> /// <param name="Url">url</param> /// <param name="postString">Post数据</param> /// <returns></returns> public string PostString_UTF8(string Url, string postString) { return PostString(Url, postString, Encoding.UTF8); } }
Base64帮助类:
public class Base64 { /// <summary> /// Base64加密 /// </summary> /// <param name="codeName">加密采用的编码方式</param> /// <param name="source">待加密的明文</param> /// <returns></returns> public static string EncodeBase64(Encoding encode, string source) { string result = string.Empty; byte[] bytes = encode.GetBytes(source); try { result = Convert.ToBase64String(bytes); } catch { result = source; } return result; } /// <summary> /// Base64加密,采用utf8编码方式加密 /// </summary> /// <param name="source">待加密的明文</param> /// <returns>加密后的字符串</returns> public static string EncodeBase64(string source) { return EncodeBase64(Encoding.UTF8, source); } /// <summary> /// Base64解密 /// </summary> /// <param name="codeName">解密采用的编码方式,注意和加密时采用的方式一致</param> /// <param name="result">待解密的密文</param> /// <returns>解密后的字符串</returns> public static string DecodeBase64(Encoding encode, string result) { string decode = ""; byte[] bytes = Convert.FromBase64String(result); try { decode = encode.GetString(bytes); } catch { decode = result; } return decode; } /// <summary> /// Base64解密,采用utf8编码方式解密 /// </summary> /// <param name="result">待解密的密文</param> /// <returns>解密后的字符串</returns> public static string DecodeBase64(string result) { return DecodeBase64(Encoding.UTF8, result); } /// <summary> /// Base64解密,采用utf8编码方式解密 /// </summary> /// <param name="result">待解密的密文</param> /// <returns>解密后的字符串</returns> public static string DecodeBase64IgnoreEmpty(string result) { return DecodeBase64(Encoding.UTF8, result.Replace("+", "%2B")); } /// <summary> /// Base64加密,采用utf8编码方式加密 /// </summary> /// <param name="source">待加密的明文</param> /// <returns>加密后的字符串</returns> public static string EncodeBase64IgnoreEmpty(string source) { return EncodeBase64(Encoding.UTF8, source.Replace("%2B", "+")); } }
EncryptHelper帮助类:
public class EncryptHelper { /// <summary> /// MD5 /// </summary> /// <param name="str"></param> /// <param name="code"></param> /// <returns></returns> public static string MD5(string str, int code) { if (code == 16) //16位MD5加密(取32位加密的9~25字符) { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16); } if (code == 32) //32位加密 { return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower(); } return "00000000000000000000000000000000"; } /// <summary> /// AES加密函数(128位) 加密模式:AES/CBC/PKCS5Padding 加密初始化向量:长度为 16 的空字节数组 /// </summary> /// <param name="toEncrypt"></param> /// <returns></returns> public static string Encrypt(string toEncrypt,string key) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); RijndaelManaged rDel = new RijndaelManaged(); rDel.IV = new byte[16]; rDel.Key = keyArray; rDel.Mode = CipherMode.CBC; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateEncryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return Convert.ToBase64String(resultArray, 0, resultArray.Length); } /// <summary> /// AES解密函数(128位) /// </summary> /// <param name="toDecrypt"></param> /// <returns></returns> public static string Decrypt(string toDecrypt, string key) { byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key); byte[] toEncryptArray = Convert.FromBase64String(toDecrypt); RijndaelManaged rDel = new RijndaelManaged(); rDel.IV = new byte[16]; rDel.Key = keyArray; rDel.Mode = CipherMode.CBC; rDel.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = rDel.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length); return UTF8Encoding.UTF8.GetString(resultArray); } public static string Encrypt2(string toEncrypt) { StringBuilder sb = new StringBuilder(); int asc = 0; foreach (char c in toEncrypt) { asc = (int)c; sb.Append(Convert.ToString(asc, 8) + "9"); } return sb.ToString(); } public static string Decrypt2(string toEncrypt) { string[] ss = toEncrypt.Split(new char[] { ‘9‘ }, StringSplitOptions.RemoveEmptyEntries); StringBuilder sb = new StringBuilder(); foreach (string s in ss) { sb.Append(Convert.ToChar(Convert.ToInt32(s, 8)).ToString()); } return sb.ToString(); } /// <summary> /// GZip解压 /// </summary> /// <param name="inputStr"></param> /// <returns></returns> public static string Decompress(string inputStr) { byte[] bs = Convert.FromBase64String(inputStr); MemoryStream ms = new MemoryStream(bs); GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress); string result = ""; using (StreamReader sr = new StreamReader(zipStream)) { result = sr.ReadToEnd(); } zipStream.Close(); ms.Dispose(); ms.Close(); return result; } /// <summary> /// GZip压缩 /// </summary> /// <param name="inputStr"></param> /// <returns></returns> public static byte[] Compress(string inputStr) { //if (string.IsNullOrEmpty(inputStr)) //{ // return ""; //} byte[] bs = Encoding.UTF8.GetBytes(inputStr); MemoryStream ms = new MemoryStream(); using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress, true)) { zipStream.Write(bs, 0, bs.Length); } return ms.ToArray(); //byte[] res = ms.ToArray(); //ms.Dispose(); //ms.Close(); //return Convert.ToBase64String(res); } }
时间: 2024-10-13 21:16:08