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

作者:shichen2014 时间:2023-02-10 16:28:11 

本文实例讲述了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,Https,类
0
投稿

猜你喜欢

  • springboot 使用QQ邮箱发送邮件的操作方法

    2022-03-03 14:36:22
  • JavaFX 监听窗口关闭事件实例详解

    2023-07-20 21:53:06
  • android自定义控件和自定义回调函数步骤示例

    2021-07-11 15:50:50
  • Java中ShardingSphere分库分表实战

    2023-11-24 09:20:37
  • 深入解析C++编程中对设计模式中的策略模式的运用

    2022-05-26 22:52:20
  • SpringBoot中整合Minio文件存储的安装部署过程

    2022-02-21 01:28:14
  • SpringBoot快速搭建实现三步骤解析

    2021-06-12 22:33:24
  • 详解SpringCloud Config配置中心

    2021-06-18 04:38:34
  • 解决Jackson解析嵌套类问题(MismatchedInputException)

    2023-07-26 03:09:31
  • C#实现Array添加扩展实例

    2023-02-16 23:01:03
  • C#将html table 导出成excel实例

    2023-12-20 04:58:55
  • 浅谈@PostConstruct不被调用的原因

    2023-03-22 11:40:29
  • Java实现删除排序链表中的重复元素的方法

    2022-11-28 08:27:22
  • android采用FFmpeg实现音视频合成与分离

    2022-03-05 09:18:16
  • 提高C# StringBuilder操作性能优化的方法

    2023-04-26 01:16:13
  • Android EditText限制输入字符类型的方法总结

    2023-10-11 15:48:19
  • C++实现企业职工工资管理系统

    2023-11-02 17:34:34
  • IDEA安装详细步骤(多图预警)

    2022-02-28 14:38:39
  • 通过实例解析java8中的parallelStream

    2022-04-17 12:59:37
  • SpringBoot如何优雅的整合Swagger Api自动生成文档

    2022-08-10 00:49:29
  • asp之家 软件编程 m.aspxhome.com