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


      1 using System.Text;
      2 using System.Net;
      3 using System.IO;
      4 using System.Text.RegularExpressions;
      5 using System.Security.Cryptography.X509Certificates;
      6 using System.Net.Security;
      7 namespace WebRequestTest
      8 {
      9     /// <summary>
     10     /// 动态类,每个实例使用单独session
     11     /// </summary>
     12     public class HttpHelperNew
     13     {
     14        public CookieContainer cookie = new CookieContainer(); 
     15         /// <summary>
     16         /// post请求返回html
     17         /// </summary>
     18         /// <param name="Url"></param>
     19         /// <param name="postDataStr"></param>
     20         /// <returns></returns>
     21         public string HttpPost(string Url, string postDataStr)
     22         {
     23             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
     24             //request.AllowAutoRedirect = false; //禁止自动重定向
     25             request.Method = "POST";
     26             request.ContentType = "application/x-www-form-urlencoded";
     27             request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
     28             request.CookieContainer = cookie; //cookie信息由CookieContainer自行维护
     29             Stream myRequestStream = request.GetRequestStream();
     30             StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
     31             myStreamWriter.Write(postDataStr);
     32             myStreamWriter.Close();
     33             HttpWebResponse response = null;
     34             try
     35             {
     36                 this.SetCertificatePolicy();
     37                 response = (HttpWebResponse)request.GetResponse();
     38             }
     39             catch (System.Exception ex)
     40             {
     41             }
     42             //获取重定向地址
     43             //string url1 = response.Headers["Location"];
     44             if (response !=null)
     45             {
     46                 Stream myResponseStream = response.GetResponseStream();
     47                 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
     48                 string retString = myStreamReader.ReadToEnd();
     49                 myStreamReader.Close();
     50                 myResponseStream.Close();
     51                 return retString;
     52             }
     53             else
     54             {
     55                 return "error"; //post请求返回为空
     56             }
     57         }
     58         /// <summary>
     59         /// get请求获取返回的html
     60         /// </summary>
     61         /// <param name="Url"></param>
     62         /// <param name="postDataStr"></param>
     63         /// <returns></returns>
     64         public string HttpGet(string Url, string Querydata)
     65         {
     66             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (Querydata == "" ? "" : "?") + Querydata);
     67             request.Method = "GET";
     68             request.ContentType = "text/html;charset=UTF-8";
     69             request.CookieContainer = cookie;
     70             this.SetCertificatePolicy();
     71             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
     72            // response.Cookies = cookie.GetCookies(response.ResponseUri);
     73             Stream myResponseStream = response.GetResponseStream();
     74             StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
     75             string retString = myStreamReader.ReadToEnd();
     76             myStreamReader.Close();
     77             myResponseStream.Close();
     78             return retString;
     79         }
     80         /// <summary>
     81         /// 获得响应中的图像
     82         /// </summary>
     83         /// <param name="url"></param>
     84         /// <returns></returns>
     85         public Stream GetResponseImage(string url)
     86         {
     87             Stream resst = null;
     88             try
     89             {
     90                 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
     91                 req.KeepAlive = true;
     92                 req.Method = "GET";
     93                 req.AllowAutoRedirect = true;
     94                 req.CookieContainer = cookie;
     95                 req.ContentType = "application/x-www-form-urlencoded";
     96                 req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
     97                 req.Timeout = 50000;
     98                 Encoding myEncoding = Encoding.GetEncoding("UTF-8");
     99                 this.SetCertificatePolicy();
    100                 HttpWebResponse res = (HttpWebResponse)req.GetResponse();
    101                 resst = res.GetResponseStream();
    102                 return resst;
    103             }
    104             catch
    105             {
    106                 return null;
    107             }
    108         }
    109         /// <summary>
    110         /// 正则获取匹配的第一个值
    111         /// </summary>
    112         /// <param name="html"></param>
    113         /// <param name="pattern"></param>
    114         /// <returns></returns>
    115         public string getStringByRegex(string html,string pattern)
    116         {
    117             Regex re = new Regex(pattern, RegexOptions.IgnoreCase);
    118             MatchCollection matchs = re.Matches(html);
    119             if (matchs.Count > 0)
    120             {
    121                 return matchs[0].Groups[1].Value;
    122             }
    123             else
    124                 return "";
    125         }
    126         /// <summary>
    127         /// 正则验证返回的response是否正确
    128         /// </summary>
    129         /// <param name="html"></param>
    130         /// <param name="pattern"></param>
    131         /// <returns></returns>
    132         public bool verifyResponseHtml(string html ,string pattern)
    133         {
    134             Regex re = new Regex(pattern);
    135             return re.IsMatch(html);
    136         }
    137         //注册证书验证回调事件,在请求之前注册
    138         private void SetCertificatePolicy()
    139         {
    140             ServicePointManager.ServerCertificateValidationCallback
    141                        += RemoteCertificateValidate;
    142         }
    143         /// <summary>  
    144         /// 远程证书验证,固定返回true 
    145         /// </summary>  
    146         private static bool RemoteCertificateValidate(object sender, X509Certificate cert,
    147             X509Chain chain, SslPolicyErrors error)
    148         {
    149             return true;
    150         }  
    151     }
    152 }
  • 相关阅读:
    forward和redirect的区别详解
    j2ee部分jar包的作用
    Struts2的工作原理(图解)详解
    struts2的s:iterator 标签 详解
    Struts2 控制标签:<s:if>、<s:elseif>和<s:else>
    Struts2 资源配置文件国际化详解
    ActionContext和ServletActionContext区别以及action访问servlet API的三种方法
    js获取class
    怎么解决eclipse报PermGen space异常的问题
    SQL模糊查找语句详解
  • 原文地址:https://www.cnblogs.com/pocn/p/5651392.html
Copyright © 2020-2023  润新知