Util.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6. using System.Web;
  7. using System.Net;
  8. using System.IO;
  9. namespace LYFZ.Weixin.SDK.Helpers
  10. {
  11. public class Util
  12. {
  13. /// <summary>
  14. /// Sha1
  15. /// </summary>
  16. /// <param name="orgStr"></param>
  17. /// <param name="encode"></param>
  18. /// <returns></returns>
  19. public static string Sha1(string orgStr, string encode = "UTF-8")
  20. {
  21. var sha1 = new SHA1Managed();
  22. var sha1bytes = System.Text.Encoding.GetEncoding(encode).GetBytes(orgStr);
  23. byte[] resultHash = sha1.ComputeHash(sha1bytes);
  24. string sha1String = BitConverter.ToString(resultHash).ToLower();
  25. sha1String = sha1String.Replace("-", "");
  26. return sha1String;
  27. }
  28. public static string MD5(string encypStr, string charset = "UTF-8")
  29. {
  30. string retStr;
  31. MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();
  32. //创建md5对象
  33. byte[] inputBye;
  34. byte[] outputBye;
  35. //使用GB2312编码方式把字符串转化为字节数组.
  36. try
  37. {
  38. inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);
  39. }
  40. catch
  41. {
  42. inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);
  43. }
  44. outputBye = m5.ComputeHash(inputBye);
  45. retStr = System.BitConverter.ToString(outputBye);
  46. retStr = retStr.Replace("-", "").ToUpper();
  47. return retStr;
  48. }
  49. private static string[] strs = new string[]
  50. {
  51. "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
  52. "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"
  53. };
  54. /// <summary>
  55. /// 创建随机字符串
  56. /// </summary>
  57. /// <returns></returns>
  58. public static string CreateNonce_str()
  59. {
  60. Random r = new Random();
  61. var sb = new StringBuilder();
  62. var length = strs.Length;
  63. for (int i = 0; i < 15; i++)
  64. {
  65. sb.Append(strs[r.Next(length - 1)]);
  66. }
  67. return sb.ToString();
  68. }
  69. /// <summary>
  70. /// 创建时间戳
  71. /// </summary>
  72. /// <returns></returns>
  73. public static long CreateTimestamp()
  74. {
  75. return (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
  76. }
  77. /// <summary>
  78. /// html转义
  79. /// </summary>
  80. /// <param name="instr"></param>
  81. /// <returns></returns>
  82. public static string Transfer(string instr)
  83. {
  84. if (instr == null) return "";
  85. return instr.Replace("&", "&amp;").Replace("<", "&lt;")
  86. .Replace(">", "&gt;").Replace("\"", "&quot;");
  87. }
  88. /// <summary>
  89. /// html转义字符串还原
  90. /// </summary>
  91. /// <param name="instr"></param>
  92. /// <returns></returns>
  93. public static string DeTransfer(string instr)
  94. {
  95. if (instr == null) return "";
  96. return instr.Replace("&amp;", "&").Replace("&lt;", "<")
  97. .Replace("&gt;", ">").Replace("&quot;", "\"");
  98. }
  99. /// <summary>
  100. /// FORM表单POST方式上传一个多媒体文件
  101. /// </summary>
  102. /// <param name="url">API URL</param>
  103. /// <param name="typeName"></param>
  104. /// <param name="fileName"></param>
  105. /// <param name="fs"></param>
  106. /// <param name="encoding"></param>
  107. /// <returns></returns>
  108. public static string HttpRequestPost(string url, string typeName, string fileName, Stream fs, string encoding = "UTF-8")
  109. {
  110. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  111. request.Method = "POST";
  112. request.Timeout = 10000;
  113. var postStream = new MemoryStream();
  114. #region 处理Form表单文件上传
  115. //通过表单上传文件
  116. string boundary = "----" + DateTime.Now.Ticks.ToString("x");
  117. string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
  118. try
  119. {
  120. var formdata = string.Format(formdataTemplate, typeName, fileName);
  121. var formdataBytes = Encoding.ASCII.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行
  122. postStream.Write(formdataBytes, 0, formdataBytes.Length);
  123. //写入文件
  124. byte[] buffer = new byte[1024];
  125. int bytesRead = 0;
  126. while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
  127. {
  128. postStream.Write(buffer, 0, bytesRead);
  129. }
  130. }
  131. catch (Exception ex)
  132. {
  133. throw ex;
  134. }
  135. //结尾
  136. var footer = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
  137. postStream.Write(footer, 0, footer.Length);
  138. request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
  139. #endregion
  140. request.ContentLength = postStream != null ? postStream.Length : 0;
  141. request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
  142. request.KeepAlive = true;
  143. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
  144. #region 输入二进制流
  145. if (postStream != null)
  146. {
  147. postStream.Position = 0;
  148. //直接写入流
  149. Stream requestStream = request.GetRequestStream();
  150. byte[] buffer = new byte[1024];
  151. int bytesRead = 0;
  152. while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
  153. {
  154. requestStream.Write(buffer, 0, bytesRead);
  155. }
  156. postStream.Close();//关闭文件访问
  157. }
  158. #endregion
  159. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  160. using (Stream responseStream = response.GetResponseStream())
  161. {
  162. using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding(encoding)))
  163. {
  164. string retString = myStreamReader.ReadToEnd();
  165. return retString;
  166. }
  167. }
  168. }
  169. /// <summary>
  170. /// 下载
  171. /// </summary>
  172. /// <param name="url"></param>
  173. /// <param name="stream"></param>
  174. public static void Download(string url, Stream stream)
  175. {
  176. WebClient wc = new WebClient();
  177. var data = wc.DownloadData(url);
  178. foreach (var b in data)
  179. {
  180. stream.WriteByte(b);
  181. }
  182. }
  183. }
  184. }