HttpService.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. public static string HttpPost(string Url, string postDataStr)
  181. {
  182. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  183. request.Method = "POST";
  184. request.ContentType = "application/x-www-form-urlencoded";
  185. request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);//Encoding.UTF8.GetByteCount(postDataStr);
  186. //request.CookieContainer = cookie;
  187. Stream myRequestStream = request.GetRequestStream();
  188. //StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8"));
  189. //myStreamWriter.Write(postDataStr);
  190. //myStreamWriter.Close();
  191. byte[] bt = Encoding.UTF8.GetBytes(postDataStr);
  192. myRequestStream.Write(bt, 0, Encoding.UTF8.GetByteCount(postDataStr));
  193. myRequestStream.Close();
  194. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  195. //Log.Error(this.GetType().ToString(), "1:");
  196. //response.Cookies = cookie.GetCookies(response.ResponseUri);
  197. Stream myResponseStream = response.GetResponseStream();
  198. //Log.Error(this.GetType().ToString(), "2:");
  199. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
  200. string retString = myStreamReader.ReadToEnd();
  201. //Log.Error(this.GetType().ToString(), "3:");
  202. myStreamReader.Close();
  203. myResponseStream.Close();
  204. return retString;
  205. }
  206. }
  207. }