当前位置: 首页 > 编程笔记 >

C#模拟Http与Https请求框架类实例

刘瑞
2023-03-14
本文向大家介绍C#模拟Http与Https请求框架类实例,包括了C#模拟Http与Https请求框架类实例的使用技巧和注意事项,需要的朋友参考一下

本文实例讲述了C#模拟Http与Https请求框架类。分享给大家供大家参考。

具体实现方法如下:


using System.Text;

using System.Net;

using System.IO;

using System.Text.RegularExpressions;

using System.Security.Cryptography.X509Certificates;

using System.Net.Security;

namespace WebRequestTest {     /// <summary>     /// 动态类,每个实例使用单独session     /// </summary>     public class HttpHelperNew     {        public CookieContainer cookie = new CookieContainer();         /// <summary>         /// post请求返回html         /// </summary>         /// <param name="Url"></param>         /// <param name="postDataStr"></param>         /// <returns></returns>         public string HttpPost(string Url, string postDataStr)         {             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);             //request.AllowAutoRedirect = false; //禁止自动重定向             request.Method = "POST";             request.ContentType = "application/x-www-form-urlencoded";             request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);             request.CookieContainer = cookie; //cookie信息由CookieContainer自行维护             Stream myRequestStream = request.GetRequestStream();             StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));             myStreamWriter.Write(postDataStr);             myStreamWriter.Close();

            HttpWebResponse response = null;             try             {                 this.SetCertificatePolicy();                 response = (HttpWebResponse)request.GetResponse();             }             catch (System.Exception ex)             {             }             //获取重定向地址             //string url1 = response.Headers["Location"];             if (response !=null)             {                 Stream myResponseStream = response.GetResponseStream();                 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));                 string retString = myStreamReader.ReadToEnd();                 myStreamReader.Close();                 myResponseStream.Close();                 return retString;             }             else             {                 return "error"; //post请求返回为空             }         }

        /// <summary>         /// get请求获取返回的html         /// </summary>         /// <param name="Url"></param>         /// <param name="postDataStr"></param>         /// <returns></returns>         public string HttpGet(string Url, string Querydata)         {             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (Querydata == "" ? "" : "?") + Querydata);             request.Method = "GET";             request.ContentType = "text/html;charset=UTF-8";             request.CookieContainer = cookie;             this.SetCertificatePolicy();             HttpWebResponse response = (HttpWebResponse)request.GetResponse();            // response.Cookies = cookie.GetCookies(response.ResponseUri);             Stream myResponseStream = response.GetResponseStream();             StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));             string retString = myStreamReader.ReadToEnd();             myStreamReader.Close();             myResponseStream.Close();             return retString;         }

        /// <summary>         /// 获得响应中的图像         /// </summary>         /// <param name="url"></param>         /// <returns></returns>         public Stream GetResponseImage(string url)         {             Stream resst = null;             try             {                 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);                 req.KeepAlive = true;                 req.Method = "GET";                 req.AllowAutoRedirect = true;                 req.CookieContainer = cookie;                 req.ContentType = "application/x-www-form-urlencoded";                 req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";                 req.Timeout = 50000;

                Encoding myEncoding = Encoding.GetEncoding("UTF-8");                 this.SetCertificatePolicy();                 HttpWebResponse res = (HttpWebResponse)req.GetResponse();                 resst = res.GetResponseStream();

                return resst;             }             catch             {                 return null;             }         }

        /// <summary>         /// 正则获取匹配的第一个值         /// </summary>         /// <param name="html"></param>         /// <param name="pattern"></param>         /// <returns></returns>         public string getStringByRegex(string html,string pattern)         {

            Regex re = new Regex(pattern, RegexOptions.IgnoreCase);             MatchCollection matchs = re.Matches(html);             if (matchs.Count > 0)             {                 return matchs[0].Groups[1].Value;             }             else                 return "";         }

        /// <summary>         /// 正则验证返回的response是否正确         /// </summary>         /// <param name="html"></param>         /// <param name="pattern"></param>         /// <returns></returns>         public bool verifyResponseHtml(string html ,string pattern)         {             Regex re = new Regex(pattern);             return re.IsMatch(html);         }

        //注册证书验证回调事件,在请求之前注册         private void SetCertificatePolicy()         {             ServicePointManager.ServerCertificateValidationCallback                        += RemoteCertificateValidate;         }         /// <summary>          /// 远程证书验证,固定返回true         /// </summary>          private static bool RemoteCertificateValidate(object sender, X509Certificate cert,             X509Chain chain, SslPolicyErrors error)         {             return true;         }      } }

希望本文所述对大家的C#程序设计有所帮助。

 类似资料:
  • 本文向大家介绍使用C#发送Http请求实现模拟登陆实例,包括了使用C#发送Http请求实现模拟登陆实例的使用技巧和注意事项,需要的朋友参考一下 模拟登陆的原理很简单,就是发送一个Http 请求服务器获得响应,然后客户端获取到cookie即可实现模拟登陆,比如一些抢票软件的原理无非也是这样模拟客户端的cookie 然后发送请求去抢票,然后12306 本文将演示如何用C# 来实现模拟登陆的,推荐一款工

  • 网络爬虫工作过程可以理解为模拟浏览器操作的过程,浏览器的主要功能是向服务器发出请求,在浏览器窗口中展示服务器返回的网络资源。 一、浏览器处理网页的过程 我们先来看一下浏览网页的基本过程,比如我们在浏览器地址栏输入:http://www.baidu.com 回车后会浏览器会显示百度的首页。 这段网络通信过程中到底发生了什么?简单来说这段过程发生了以下四个步骤: 当我们在浏览器输入URL http:/

  • 本文向大家介绍C#模拟http 发送post或get请求的简单实例,包括了C#模拟http 发送post或get请求的简单实例的使用技巧和注意事项,需要的朋友参考一下 在post的时候有时也用的到cookie,像登录163发邮件时候就需要发送cookie,所以在外部一个cookie属性随时保存 CookieContainer cookie = new CookieContainer(); 注意:有

  • 如何模拟AsNoTracking方法? 在下面的示例中,DbContext已经注入到服务类中,如果我从GetOrderedProducts方法中移除AsNoTracking扩展方法,它可以正常工作,但是with AsNoTracking测试失败,因为它返回null。我还试图模拟AsNoTracking以返回正确的值,但它不起作用。

  • 1. 前言 通过几个章节的学习,大家对于 Spring 已经有了初步的认知,我们通过案例练习,或者源码追踪,可以粗略的看到 Spring 框架初始化 bean 对象的过程,那么这个章节,我们模拟 Spring 框架的思路,来写一个类似 Spring 加载对象的案例,加深大家的印象。 2. 案例实现思路 2.1 步骤介绍 思路分析: 我们通过写过的案例可以知道: Spring 框架的容器 是一个接口