WebUtils.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using System.Web;
  8. using System.Net.Security;
  9. using System.Security.Authentication;
  10. using System.Security.Cryptography.X509Certificates;
  11. namespace cuidian.OpenApi.Http
  12. {
  13. public sealed class WebUtils
  14. {
  15. private int _timeout = 100000;
  16. /// <summary>
  17. /// 请求与响应的超时时间
  18. /// </summary>
  19. public int Timeout
  20. {
  21. get { return this._timeout; }
  22. set { this._timeout = value; }
  23. }
  24. /// <summary>
  25. /// 执行HTTP POST请求。
  26. /// </summary>
  27. /// <param name="url">请求地址</param>
  28. /// <param name="parameters">请求参数</param>
  29. /// <returns>HTTP响应</returns>
  30. public HttpWebResponse Post(string url, IDictionary<string, string> parameters, string data)
  31. {
  32. if (parameters != null && parameters.Count > 0)
  33. {
  34. if (url.Contains("?"))
  35. {
  36. url = url + "&" + BuildQuery(parameters);
  37. }
  38. else
  39. {
  40. url = url + "?" + BuildQuery(parameters);
  41. }
  42. }
  43. HttpWebRequest req = GetWebRequest(url, "POST");
  44. req.ContentType = "application/json;charset=utf-8";
  45. byte[] postData = Encoding.UTF8.GetBytes(data);
  46. System.IO.Stream reqStream = req.GetRequestStream();
  47. reqStream.Write(postData, 0, postData.Length);
  48. reqStream.Close();
  49. return (HttpWebResponse)req.GetResponse();
  50. }
  51. /// <summary>
  52. /// 执行HTTP GET请求。
  53. /// </summary>
  54. /// <param name="url">请求地址</param>
  55. /// <param name="parameters">请求参数</param>
  56. /// <returns>HTTP响应</returns>
  57. public HttpWebResponse Get(string url, IDictionary<string, string> parameters)
  58. {
  59. if (parameters != null && parameters.Count > 0)
  60. {
  61. if (url.Contains("?"))
  62. {
  63. url = url + "&" + BuildQuery(parameters);
  64. }
  65. else
  66. {
  67. url = url + "?" + BuildQuery(parameters);
  68. }
  69. }
  70. Console.WriteLine("url:" + url);
  71. HttpWebRequest req = GetWebRequest(url, "GET");
  72. req.ContentType = "application/json;charset=utf-8";
  73. return (HttpWebResponse)req.GetResponse();
  74. }
  75. public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  76. { //直接确认,否则打不开
  77. return true;
  78. }
  79. public HttpWebRequest GetWebRequest(string url, string method)
  80. {
  81. HttpWebRequest req = null;
  82. if (url.Contains("https"))
  83. {
  84. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  85. req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
  86. }
  87. else
  88. {
  89. req = (HttpWebRequest)WebRequest.Create(url);
  90. }
  91. req.ServicePoint.Expect100Continue = false;
  92. req.Method = method;
  93. req.KeepAlive = true;
  94. req.UserAgent = "openapi4net:open.yonyouup.com";
  95. req.Timeout = this._timeout;
  96. return req;
  97. }
  98. /// <summary>
  99. /// 把响应流转换为文本。
  100. /// </summary>
  101. /// <param name="rsp">响应流对象</param>
  102. /// <param name="encoding">编码方式</param>
  103. /// <returns>响应文本</returns>
  104. public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
  105. {
  106. System.IO.Stream stream = null;
  107. StreamReader reader = null;
  108. try
  109. {
  110. // 以字符流的方式读取HTTP响应
  111. stream = rsp.GetResponseStream();
  112. reader = new StreamReader(stream, encoding);
  113. return reader.ReadToEnd();
  114. }
  115. finally
  116. {
  117. // 释放资源
  118. if (reader != null) reader.Close();
  119. if (stream != null) stream.Close();
  120. if (rsp != null) rsp.Close();
  121. }
  122. }
  123. /// <summary>
  124. /// 组装GET请求URL。
  125. /// </summary>
  126. /// <param name="url">请求地址</param>
  127. /// <param name="parameters">请求参数</param>
  128. /// <returns>带参数的GET请求URL</returns>
  129. public string BuildGetUrl(string url, IDictionary<string, string> parameters)
  130. {
  131. if (parameters != null && parameters.Count > 0)
  132. {
  133. if (url.Contains("?"))
  134. {
  135. url = url + "&" + BuildQuery(parameters);
  136. }
  137. else
  138. {
  139. url = url + "?" + BuildQuery(parameters);
  140. }
  141. }
  142. return url;
  143. }
  144. /// <summary>
  145. /// 组装普通文本请求参数。
  146. /// </summary>
  147. /// <param name="parameters">Key-Value形式请求参数字典</param>
  148. /// <returns>URL编码后的请求数据</returns>
  149. public static string BuildQuery(IDictionary<string, string> parameters)
  150. {
  151. StringBuilder postData = new StringBuilder();
  152. bool hasParam = false;
  153. IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
  154. while (dem.MoveNext())
  155. {
  156. string name = dem.Current.Key;
  157. string value = dem.Current.Value;
  158. // 忽略参数名或参数值为空的参数
  159. if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
  160. {
  161. if (hasParam)
  162. {
  163. postData.Append("&");
  164. }
  165. postData.Append(name);
  166. postData.Append("=");
  167. postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
  168. hasParam = true;
  169. }
  170. }
  171. return postData.ToString();
  172. }
  173. }
  174. }