HttpService.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. X509Certificate2 cert = new X509Certificate2(WxPayConfig.SSLCERT_PATH, WxPayConfig.SSLCERT_PASSWORD, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet);
  61. request.ClientCertificates.Add(cert);
  62. Log.Debug("WxPayApi", "PostXml used cert");
  63. }
  64. //往服务器写入数据
  65. reqStream = request.GetRequestStream();
  66. reqStream.Write(data, 0, data.Length);
  67. reqStream.Close();
  68. //获取服务端返回
  69. response = (HttpWebResponse)request.GetResponse();
  70. //获取服务端返回数据
  71. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  72. result = sr.ReadToEnd().Trim();
  73. sr.Close();
  74. }
  75. catch (System.Threading.ThreadAbortException e)
  76. {
  77. Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
  78. Log.Error("Exception message: {0}", e.Message);
  79. System.Threading.Thread.ResetAbort();
  80. }
  81. catch (WebException e)
  82. {
  83. Log.Error("HttpService", e.ToString());
  84. if (e.Status == WebExceptionStatus.ProtocolError)
  85. {
  86. Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
  87. Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
  88. }
  89. throw new WxPayException(e.ToString());
  90. }
  91. catch (Exception e)
  92. {
  93. Log.Error("HttpService", e.ToString());
  94. throw new WxPayException(e.ToString());
  95. }
  96. finally
  97. {
  98. //关闭连接和流
  99. if (response != null)
  100. {
  101. response.Close();
  102. }
  103. if (request != null)
  104. {
  105. request.Abort();
  106. }
  107. }
  108. return result;
  109. }
  110. /// <summary>
  111. /// 处理http GET请求,返回数据
  112. /// </summary>
  113. /// <param name="url">请求的url地址</param>
  114. /// <returns>http GET成功后返回的数据,失败抛WebException异常</returns>
  115. public static string Get(string url)
  116. {
  117. System.GC.Collect();
  118. string result = "";
  119. HttpWebRequest request = null;
  120. HttpWebResponse response = null;
  121. //请求url以获取数据
  122. try
  123. {
  124. //设置最大连接数
  125. ServicePointManager.DefaultConnectionLimit = 200;
  126. //设置https验证方式
  127. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  128. {
  129. ServicePointManager.ServerCertificateValidationCallback =
  130. new RemoteCertificateValidationCallback(CheckValidationResult);
  131. }
  132. /***************************************************************
  133. * 下面设置HttpWebRequest的相关属性
  134. * ************************************************************/
  135. request = (HttpWebRequest)WebRequest.Create(url);
  136. request.Method = "GET";
  137. //设置代理
  138. //WebProxy proxy = new WebProxy();
  139. //proxy.Address = new Uri(WxPayConfig.PROXY_URL);
  140. //request.Proxy = proxy;
  141. //获取服务器返回
  142. response = (HttpWebResponse)request.GetResponse();
  143. //获取HTTP返回数据
  144. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  145. result = sr.ReadToEnd().Trim();
  146. sr.Close();
  147. }
  148. catch (System.Threading.ThreadAbortException e)
  149. {
  150. Log.Error("HttpService", "Thread - caught ThreadAbortException - resetting.");
  151. Log.Error("Exception message: {0}", e.Message);
  152. System.Threading.Thread.ResetAbort();
  153. }
  154. catch (WebException e)
  155. {
  156. Log.Error("HttpService", e.ToString());
  157. if (e.Status == WebExceptionStatus.ProtocolError)
  158. {
  159. Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
  160. Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
  161. }
  162. throw new WxPayException(e.ToString());
  163. }
  164. catch (Exception e)
  165. {
  166. Log.Error("HttpService", e.ToString());
  167. throw new WxPayException(e.ToString());
  168. }
  169. finally
  170. {
  171. //关闭连接和流
  172. if (response != null)
  173. {
  174. response.Close();
  175. }
  176. if (request != null)
  177. {
  178. request.Abort();
  179. }
  180. }
  181. return result;
  182. }
  183. }
  184. }