25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

202 satır
7.8 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Web;
  4. using System.Net;
  5. using System.IO;
  6. using System.Text;
  7. using System.Net.Security;
  8. using System.Security.Authentication;
  9. using System.Security.Cryptography.X509Certificates;
  10. namespace WxPayAPI
  11. {
  12. /// <summary>
  13. /// http连接基础类,负责底层的http通信
  14. /// </summary>
  15. public class HttpService
  16. {
  17. public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  18. {
  19. //直接确认,否则打不开
  20. return true;
  21. }
  22. public static string Post(string xml, string url, bool isUseCert, int timeout)
  23. {
  24. System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接
  25. string result = "";//返回结果
  26. HttpWebRequest request = null;
  27. HttpWebResponse response = null;
  28. Stream reqStream = null;
  29. try
  30. {
  31. //设置最大连接数
  32. ServicePointManager.DefaultConnectionLimit = 200;
  33. //设置https验证方式
  34. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  35. {
  36. ServicePointManager.ServerCertificateValidationCallback =
  37. new RemoteCertificateValidationCallback(CheckValidationResult);
  38. }
  39. /***************************************************************
  40. * HttpWebRequest的相关属性
  41. * ************************************************************/
  42. request = (HttpWebRequest)WebRequest.Create(url);
  43. request.Method = "POST";
  44. request.Timeout = timeout * 1000;
  45. //设置代理服务器
  46. //WebProxy proxy = new WebProxy(); //定义一个网关对象
  47. //proxy.Address = new Uri(WxPayConfig.PROXY_URL); //网关服务器端口:端口
  48. //request.Proxy = proxy;
  49. //设置POST的数据类型和长度
  50. request.ContentType = "text/xml";
  51. byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);
  52. request.ContentLength = data.Length;
  53. //是否使用证书
  54. if (isUseCert)
  55. {
  56. string path = HttpContext.Current.Request.PhysicalApplicationPath;
  57. X509Certificate2 cert = new X509Certificate2(path + WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD);
  58. request.ClientCertificates.Add(cert);
  59. Log.Debug("WxPayApi", "PostXml used cert");
  60. }
  61. //往服务器写入数据
  62. reqStream = request.GetRequestStream();
  63. reqStream.Write(data, 0, data.Length);
  64. reqStream.Close();
  65. //获取服务端返回
  66. response = (HttpWebResponse)request.GetResponse();
  67. //获取服务端返回数据
  68. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  69. result = sr.ReadToEnd().Trim();
  70. sr.Close();
  71. }
  72. catch (System.Threading.ThreadAbortException e)
  73. {
  74. Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
  75. Log.Error("Exception message: {0}", e.Message);
  76. System.Threading.Thread.ResetAbort();
  77. }
  78. catch (WebException e)
  79. {
  80. Log.Error("HttpService", e.ToString());
  81. if (e.Status == WebExceptionStatus.ProtocolError)
  82. {
  83. Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
  84. Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
  85. }
  86. throw new WxPayException(e.ToString());
  87. }
  88. catch (Exception e)
  89. {
  90. Log.Error("HttpService", e.ToString());
  91. throw new WxPayException(e.ToString());
  92. }
  93. finally
  94. {
  95. //关闭连接和流
  96. if (response != null)
  97. {
  98. response.Close();
  99. }
  100. if(request != null)
  101. {
  102. request.Abort();
  103. }
  104. }
  105. return result;
  106. }
  107. /// <summary>
  108. /// 处理http GET请求,返回数据
  109. /// </summary>
  110. /// <param name="url">请求的url地址</param>
  111. /// <returns>http GET成功后返回的数据,失败抛WebException异常</returns>
  112. public static string Get(string url)
  113. {
  114. System.GC.Collect();
  115. string result = "";
  116. HttpWebRequest request = null;
  117. HttpWebResponse response = null;
  118. //请求url以获取数据
  119. try
  120. {
  121. //设置最大连接数
  122. ServicePointManager.DefaultConnectionLimit = 200;
  123. //设置https验证方式
  124. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  125. {
  126. ServicePointManager.ServerCertificateValidationCallback =
  127. new RemoteCertificateValidationCallback(CheckValidationResult);
  128. }
  129. /***************************************************************
  130. * HttpWebRequest的相关属性
  131. * ************************************************************/
  132. request = (HttpWebRequest)WebRequest.Create(url);
  133. request.Method = "GET";
  134. //设置代理
  135. //WebProxy proxy = new WebProxy();
  136. //proxy.Address = new Uri(WxPayConfig.PROXY_URL);
  137. //request.Proxy = proxy;
  138. //获取服务器返回
  139. response = (HttpWebResponse)request.GetResponse();
  140. //获取HTTP返回数据
  141. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  142. result = sr.ReadToEnd().Trim();
  143. sr.Close();
  144. }
  145. catch (System.Threading.ThreadAbortException e)
  146. {
  147. Log.Error("HttpService","Thread - caught ThreadAbortException - resetting.");
  148. Log.Error("Exception message: {0}", e.Message);
  149. System.Threading.Thread.ResetAbort();
  150. }
  151. catch (WebException e)
  152. {
  153. Log.Error("HttpService", e.ToString());
  154. if (e.Status == WebExceptionStatus.ProtocolError)
  155. {
  156. Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
  157. Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
  158. }
  159. throw new WxPayException(e.ToString());
  160. }
  161. catch (Exception e)
  162. {
  163. Log.Error("HttpService", e.ToString());
  164. throw new WxPayException(e.ToString());
  165. }
  166. finally
  167. {
  168. //关闭连接和流
  169. if (response != null)
  170. {
  171. response.Close();
  172. }
  173. if (request != null)
  174. {
  175. request.Abort();
  176. }
  177. }
  178. return result;
  179. }
  180. }
  181. }