HttpHelper.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. /*
  2. * 由SharpDevelop创建。
  3. * 用户: gwang
  4. * 日期: 2016/5/3
  5. * 时间: 17:20
  6. *
  7. * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
  8. */
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Net;
  14. using System.Text;
  15. //using CSharpUtil.RSA;
  16. namespace CSharpUtil.Net
  17. {
  18. /// <summary>
  19. /// Http辅助类.
  20. /// </summary>
  21. public class HttpHelper
  22. {
  23. /// <summary>
  24. /// 自定义异常,编码不合约定(Get=>Base64,Post=>deflate)
  25. /// </summary>
  26. class EncodeException : Exception
  27. {
  28. public EncodeException()
  29. : base("编码")
  30. {
  31. }
  32. }
  33. /// <summary>
  34. /// 自定义的User-Agent
  35. /// </summary>
  36. const string userAgent = "WebRequest/mail@wanggangzero.cn";
  37. private static HttpHelper mInst = mInst ?? new HttpHelper();
  38. /// <summary>
  39. /// 单例
  40. /// </summary>
  41. public static HttpHelper Instance { get => mInst; }
  42. private IWebProxy mProxy = new WebProxy();
  43. /// <summary>
  44. /// 可以指定代理服务器
  45. /// </summary>
  46. public IWebProxy Proxy { get => mProxy; set => mProxy = value; }
  47. public string Post(string url, string data) => mWebRequest(url, data, "POST", Encoding.UTF8);
  48. private HttpWebRequest mGetWebRequest(string url, string method)
  49. {
  50. var webReq = (HttpWebRequest)WebRequest.Create(new Uri(url));
  51. webReq.Method = method;
  52. webReq.KeepAlive = true;
  53. webReq.UserAgent = userAgent;
  54. webReq.Proxy = mProxy;
  55. return webReq;
  56. }
  57. private string mWebRequest(string url, string data, string method, Encoding encode)
  58. {
  59. var ret = string.Empty;
  60. var getUrl = (method.ToUpper() == "GET") ? url + "?" + data : url;
  61. var webReq = mGetWebRequest(getUrl, method);
  62. if (method.ToUpper() == "POST")
  63. { // 写post流
  64. webReq.ServicePoint.Expect100Continue = false; // Post优化,去掉问答流程,提速,避免一些服务器不支持.
  65. try
  66. {
  67. using (var nstream = webReq.GetRequestStream())
  68. {
  69. var byteArray = encode.GetBytes(data);
  70. nstream.Write(byteArray, 0, byteArray.Length);
  71. }
  72. }
  73. catch (Exception e)
  74. {
  75. return "net fail";
  76. }
  77. }
  78. // 读取返回值
  79. using (var response = (HttpWebResponse)webReq.GetResponse())
  80. using (var sr = new StreamReader(response.GetResponseStream(), encode))
  81. {
  82. if (response.StatusCode != HttpStatusCode.OK)
  83. {
  84. return response.StatusDescription;
  85. }
  86. ret = sr.ReadToEnd();
  87. }
  88. return ret;
  89. }
  90. #region ` 自定义传输模式 post=>defalte,get=>base64 `
  91. /// <summary>
  92. /// 发送deflate
  93. /// </summary>
  94. /// <param name="url"></param>
  95. /// <param name="data"></param>
  96. /// <param name="encode"></param>
  97. /// <returns></returns>
  98. public string PostDeflate(string url, string data, Encoding encode) => MyWebRequest(url, data, "POST", encode);
  99. public string GetBase64(string url, string data, Encoding encode) => MyWebRequest(url, data, "GET", encode);
  100. private string MyWebRequest(string url, string data, string method, Encoding encode)
  101. {
  102. var ret = string.Empty;
  103. var getUrl = (method.ToUpper() == "GET") ? url + "?" + Convert.ToBase64String(encode.GetBytes(data)) : url;
  104. var webReq = (HttpWebRequest)WebRequest.Create(new Uri(getUrl));
  105. webReq.Method = method;
  106. webReq.KeepAlive = true;
  107. webReq.UserAgent = userAgent;
  108. webReq.Proxy = mProxy;
  109. if (method.ToUpper() == "POST")
  110. { // 写post流
  111. webReq.ContentType = "application/octet-stream"; // 注意这里不使用deflate以免中间环节意外解压
  112. webReq.ServicePoint.Expect100Continue = false; // Post优化,去掉问答流程,提速,避免一些服务器不支持.
  113. using (Stream nstream = webReq.GetRequestStream())
  114. {
  115. var byteArray = CompressUtil.Deflate(encode.GetBytes(data));
  116. nstream.Write(byteArray, 0, byteArray.Length);
  117. }
  118. }
  119. // 读取返回值
  120. using (var response = (HttpWebResponse)webReq.GetResponse())
  121. {
  122. if (method.ToUpper() == "GET")
  123. {
  124. using (var sr = new StreamReader(response.GetResponseStream(), encode))
  125. {
  126. ret = encode.GetString(Convert.FromBase64String(sr.ReadToEnd()));
  127. }
  128. }
  129. else
  130. {
  131. ret = encode.GetString(CompressUtil.InFlate(response.GetResponseStream()));
  132. }
  133. }
  134. return ret;
  135. }
  136. #endregion
  137. #region ` 签名 `
  138. ///// <summary>
  139. ///// http参数签名
  140. ///// </summary>
  141. ///// <param name="dic"></param>
  142. ///// <param name="privKeyFileName"></param>
  143. ///// <returns></returns>
  144. //public static string Sign(IDictionary<string, string> dic, string privKeyFileName)
  145. //{
  146. // var queryStr = getQueryString(dic);
  147. // return RSAUtil.RSASign(queryStr, privKeyFileName);
  148. //}
  149. /// <summary>
  150. /// 将参数数组组装成URLQuerystring.
  151. /// </summary>
  152. /// <param name="parameters"></param>
  153. /// <param name="sorted"></param>
  154. /// <returns></returns>
  155. public static string getQueryString(IDictionary<string, string> parameters, bool sorted = true)
  156. {
  157. return string.Join("&", (from kv in (sorted ? parameters.OrderBy(kv => kv.Key) : parameters.AsEnumerable()) select kv.Key + "=" + kv.Value).ToArray());
  158. }
  159. #endregion
  160. }
  161. }