HttpService.cs 7.7 KB

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