HttpService.cs 7.5 KB

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