当前位置:   article > 正文

C#收发HttpWebResponse(1)——Post/Get_c# 前台如何接收response

c# 前台如何接收response

C#中收发HttpWebResponse(post和get方式)消息,以下是一个操作实例:

已封装成Http类,发送post/get方式的http请求:

  1. /// <summary>
  2. /// 有关HTTP请求的辅助类
  3. /// </summary>
  4. public class Http
  5. {
  6. private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
  7. /// <summary>
  8. /// 创建GET方式的HTTP请求
  9. /// </summary>
  10. /// <param name="url">请求的URL</param>
  11. /// <param name="timeout">请求的超时时间</param>
  12. /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
  13. /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
  14. /// <returns></returns>
  15. public static HttpWebResponse GetResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
  16. {
  17. if (string.IsNullOrEmpty(url))
  18. {
  19. throw new ArgumentNullException("url");
  20. }
  21. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  22. request.Method = "GET";
  23. request.UserAgent = DefaultUserAgent;
  24. if (!string.IsNullOrEmpty(userAgent))
  25. {
  26. request.UserAgent = userAgent;
  27. }
  28. if (timeout.HasValue)
  29. {
  30. request.Timeout = timeout.Value;
  31. }
  32. if (cookies != null)
  33. {
  34. request.CookieContainer = new CookieContainer();
  35. request.CookieContainer.Add(cookies);
  36. }
  37. return request.GetResponse() as HttpWebResponse;
  38. }
  39. /// <summary>
  40. /// 创建POST方式的HTTP请求
  41. /// </summary>
  42. /// <param name="url">请求的URL</param>
  43. /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
  44. /// <param name="timeout">请求的超时时间</param>
  45. /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
  46. /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
  47. /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
  48. /// <returns></returns>
  49. public static HttpWebResponse PostResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
  50. {
  51. if (string.IsNullOrEmpty(url))
  52. {
  53. throw new ArgumentNullException("url");
  54. }
  55. if (requestEncoding == null)
  56. {
  57. throw new ArgumentNullException("requestEncoding");
  58. }
  59. HttpWebRequest request = null;
  60. // url加随机数防止缓存,?rnd=" + Math.random();
  61. //Random random = new Random();
  62. //int rnd = random.Next(100, 999);
  63. //url += "?rnd=" + rnd.ToString();
  64. // url加时间戳
  65. url += "?rnd=" + DateTime.Now.ToString("yyyyMMddHHmmss");
  66. //如果是发送HTTPS请求
  67. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  68. {
  69. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  70. request = WebRequest.Create(url) as HttpWebRequest;
  71. request.ProtocolVersion = HttpVersion.Version10;
  72. }
  73. else
  74. {
  75. request = WebRequest.Create(url) as HttpWebRequest;
  76. }
  77. request.Method = "POST";
  78. request.ContentType = "application/x-www-form-urlencoded";
  79. if (!string.IsNullOrEmpty(userAgent))
  80. {
  81. request.UserAgent = userAgent;
  82. }
  83. else
  84. {
  85. request.UserAgent = DefaultUserAgent;
  86. }
  87. if (timeout.HasValue)
  88. {
  89. request.Timeout = timeout.Value;
  90. }
  91. if (cookies != null)
  92. {
  93. request.CookieContainer = new CookieContainer();
  94. request.CookieContainer.Add(cookies);
  95. }
  96. //如果需要POST数据
  97. if (!(parameters == null || parameters.Count == 0))
  98. {
  99. StringBuilder buffer = new StringBuilder();
  100. int i = 0;
  101. foreach (string key in parameters.Keys)
  102. {
  103. if (i > 0)
  104. {
  105. buffer.AppendFormat("&{0}={1}", key, parameters[key]);
  106. }
  107. else
  108. {
  109. buffer.AppendFormat("{0}={1}", key, parameters[key]);
  110. }
  111. i++;
  112. }
  113. byte[] data = requestEncoding.GetBytes(buffer.ToString());
  114. using (Stream stream = request.GetRequestStream())
  115. {
  116. stream.Write(data, 0, data.Length);
  117. }
  118. }
  119. HttpWebResponse response;
  120. try
  121. {
  122. response = request.GetResponse() as HttpWebResponse;
  123. }
  124. catch (Exception ex)
  125. {
  126. response = null;
  127. }
  128. return response;
  129. }
  130. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  131. {
  132. return true; //总是接受
  133. }
  134. }


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/259597
推荐阅读
相关标签
  

闽ICP备14008679号