HttpWebRequest 辅助类

using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace WebRequestHellp
{
    public class RequestHellp
    {
        private static CookieContainer ckContainer = new CookieContainer();
        private static string location = string.Empty;
        private static bool allowautoRedirect = true;
        private static string aspcookie = string.Empty;
        private static IWebProxy proxy;

        /// <summary>
        /// 获取或设置CookieContainer
        /// </summary>
        public static CookieContainer CkContainer { get => ckContainer; set => ckContainer = value; }
        /// <summary>
        /// Response后跳转链接
        /// </summary>
        public static string Location { get => location; set => location = value; }
        /// <summary>
        /// 设置Request是否自动跳转
        /// </summary>
        public static bool AllowautoRedirect { get => allowautoRedirect; set => allowautoRedirect = value; }
        /// <summary>
        /// 保留项
        /// </summary>
        public static string Aspcookie { get => aspcookie; set => aspcookie = value; }
        /// <summary>
        /// 设置代理服务器,如果需要socks5,请Nuget项目HttpToSocks5Proxy 后 using MihaZupan
        /// </summary>
        public static IWebProxy Proxy { get => proxy; set => proxy = value; }

        private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        public static int HttpHelp(string url, string method, string postdata, string referer, string ContentType, WebHeaderCollection webHeaderCollection, ref string outhtml, string Accept= null)
        {
            //解决https不安全提示
            //ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)4080; //SecurityProtocolType.Tls ; //Or SecurityProtocolType.Ssl3 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3 | SecurityProtocolType.SystemDefault;
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            ServicePointManager.DefaultConnectionLimit = 50;

            string text = string.Empty;
            string text2 = Regex.Match(url, "^(?:\\w+://)?([^/?]*)").Groups[1].Value;
            if (text2.Contains("www."))
            {
                text2 = text2.Replace("www.", "");
            }
            else
            {
                //text2 = "." + text2;
            }
            HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(url);
            if (Proxy != null)
            {
                //hwr.Proxy = new WebProxy(new Uri("socks5://" + RequestHellp.ProxyIP + ":" + RequestHellp.proxyPort));
                hwr.Proxy = Proxy;
            }
            hwr.Method = method;
            hwr.AllowAutoRedirect = AllowautoRedirect;
            hwr.KeepAlive = true;
            if (string.IsNullOrEmpty(Accept))
            {
                hwr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
            }
            else
            {
                hwr.Accept = Accept;
            }
            if (string.IsNullOrEmpty(ContentType))
            {
                //hwr.ContentType = "application/json; charset=utf-8;application/x-www-form-urlencoded";
                hwr.ContentType = "application/x-www-form-urlencoded;application/json; charset=UTF-8";
            }
            else
            {
                hwr.ContentType = ContentType;
            }
            //hwr.Headers.Add("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,ru;q=0.7,de;q=0.6");
            hwr.Headers.Add("accept-language", "en,en-US;q=0.9,en;q=0.8,ru;q=0.7,de;q=0.6");
            hwr.Headers.Add("accept-encoding", "gzip, deflate, br");
            hwr.Headers.Add("Upgrade-Insecure-szRequests", "1");
            hwr.Headers.Add("Cache-Control", "max-age=0");
            hwr.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36";
            //hwr.ContentType = "";
            if (!string.IsNullOrEmpty(referer))
            {
                hwr.Referer = referer;
            }
            if (webHeaderCollection != null)
            {
                if (webHeaderCollection.Count > 0)
                {
                    hwr.Headers.Add(webHeaderCollection);
                }
            }
            //hwr.CookieContainer = new CookieContainer();
            hwr.CookieContainer = RequestHellp.CkContainer;
            //if (string.IsNullOrEmpty(Aspcookie))
            //{
            //    hwr.Headers.Set("Cookie", Aspcookie);
            //}
            if (!string.IsNullOrEmpty(postdata))
            {
                byte[] bytes = UTF8Encoding.UTF8.GetBytes(postdata);
                hwr.ContentLength = bytes.Length;
                using (Stream stream = hwr.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Close();
                }
            }
            if (string.IsNullOrEmpty(postdata) && method.ToLower().Equals("post"))
            {
                hwr.ContentLength = 0L;
            }
            
            HttpWebResponse hwrs = null;
            try
            {
                hwrs = (HttpWebResponse)hwr.GetResponse();
            }
            catch (WebException ex)
            {
                outhtml = ex.Message;
                //using (WebResponse response = ex.Response)
                //{
                //    hwrs = response as HttpWebResponse;
                //    Debug.Print(hwrs.StatusCode.ToString());
                //    outhtml = new StreamReader(hwrs.GetResponseStream()).ReadToEnd();
                //}
                return 0;
                //throw;
            }

            //string httpresponedata = string.Empty;
            if (hwrs.ContentEncoding.ToLower().Contains("gzip"))
            {
                outhtml = new StreamReader(new GZipStream(hwrs.GetResponseStream(), CompressionMode.Decompress)).ReadToEnd();
            }
            else if (hwrs.ContentEncoding.ToLower().Contains("deflate"))
            {
                outhtml = new StreamReader(new DeflateStream(hwrs.GetResponseStream(), CompressionMode.Decompress)).ReadToEnd();
            }
            else
            {
                outhtml = new StreamReader(hwrs.GetResponseStream()).ReadToEnd();
            }
            //WebHeaderCollection webHeaderCollection = hwrs.Headers;
            //if (!string.IsNullOrEmpty(webHeaderCollection.Get("Set-Cookie")))
            //取cookie方法一
            //CookieContainer cc = new CookieContainer();
            //if (hwrs.Cookies.Count>0)
            //{
            //    foreach (Cookie cookie in hwrs.Cookies)
            //    {
            //        if (string.IsNullOrEmpty(cookie.Domain))
            //        {
            //            cookieContainer.Add(new UriBuilder(text2).Uri, cookie);
            //        }
            //        else
            //        {
            //            cookieContainer.Add(cookie);
            //        }
            //    }
            //    Form1.cookieContainer = cookieContainer;
            //    //cc = Form1.cookieContainer;
            //}
            if (!string.IsNullOrEmpty(hwrs.Headers[HttpResponseHeader.Location]))
            {
                RequestHellp.Location = hwrs.Headers[HttpResponseHeader.Location];
            }

            if (!string.IsNullOrEmpty(hwrs.Headers[HttpResponseHeader.SetCookie]))
            {
                //if (hwrs.Headers[HttpResponseHeader.SetCookie].Contains(text2))
                //{
                //    cookieContainer.SetCookies(new UriBuilder(text2).Uri, hwrs.Headers[HttpResponseHeader.SetCookie]);
                //    Form1.cookieContainer.Add(cookieContainer.GetCookies(new UriBuilder(text2).Uri));
                //    //cc = Form1.cookieContainer;
                //}
                //if (hwrs.Headers[HttpResponseHeader.SetCookie].Contains("AspNetCore.OpenIdConnect"))
                //{
                //    //Aspcookie = hwrs.Headers[HttpResponseHeader.SetCookie];
                //    //fixCookies(hwr, hwrs);
                //    FixCookies(hwr, hwrs);
                //    //string aspcookie = hwrs.Headers[HttpResponseHeader.SetCookie];
                //    //cookieContainer.SetCookies(new UriBuilder(text2).Uri, aspcookie);
                //    //Form1.cookieContainer.Add(cookieContainer.GetCookies(new UriBuilder(text2).Uri));
                //}
                RequestHellp.CkContainer.Add(GetCookies(hwr, hwrs));
                //Form1.cookieContainer.Add(GetCookies(hwrs.Headers[HttpResponseHeader.SetCookie], hwr.Host.Split(':')[0]));
            }

            return 1;
        }

        private static void fixCookies(HttpWebRequest request, HttpWebResponse response)
        {
            for (int i = 0; i < response.Headers.Count; i++)
            {
                string name = response.Headers.GetKey(i);
                if (name != "Set-Cookie")
                    continue;
                string value = response.Headers.Get(i);
                string cookies = string.Empty;
                foreach (var singleCookie in value.Split(','))
                {
                    Match match = Regex.Match(singleCookie, "(.+?)=(.+?);");
                    if (match.Captures.Count == 0)
                        continue;
                    string host = request.Host.Split(':')[0];
                    string ckname = match.Groups[1].ToString();
                    string ckvalue = match.Groups[2].ToString();
                    for (int j = 0; j < match.Groups.Count; j++)
                    {
                        try
                        {
                            RequestHellp.CkContainer.Add(new Cookie(ckname, ckvalue, "/", host));
                            if (cookies.Contains(ckname))
                            {
                                continue;
                            }
                            cookies += RequestHellp.CkContainer.GetCookieHeader(new UriBuilder(host).Uri) + "|";
                        }
                        catch (Exception)
                        {

                        }
                    }
                }
            }
        }

        private static CookieCollection GetCookies(HttpWebRequest request, HttpWebResponse response)
        {
            CookieCollection cookieCollection = new CookieCollection();
            CookieContainer cc = new CookieContainer();//调试用
            for (int i = 0; i < response.Headers.Count; i++)
            {
                string name = response.Headers.GetKey(i);
                if (name != "Set-Cookie")
                    continue;
                string value = response.Headers.Get(i);
                foreach (var cksplit in value.Split(','))
                {
                    //MatchCollection mc = Regex.Matches(cksplit, "(.+?)=(.+?);", RegexOptions.Compiled);
                    MatchCollection mc = Regex.Matches(cksplit, "(\\S*?)=(.*?)(?:;|$)", RegexOptions.Compiled);

                    string cookies = string.Empty;//调试用

                    foreach (Match item in mc)
                    {
                        if (item.Groups[1].Value.Contains("expires") || item.Groups[1].Value.Contains("path") || item.Groups[1].Value.Contains("samesite"))
                        {
                            continue;
                        }
                        try
                        {
                            string host = request.Host.Split(':')[0];
                            cookieCollection.Add(new Cookie(item.Groups[1].Value, item.Groups[2].Value, "/", host));
                            //调试用
                            cc.Add(new Cookie(item.Groups[1].Value, item.Groups[2].Value, "/", host));
                            cookies += cc.GetCookieHeader(new UriBuilder(host).Uri) + "|";
                            //调试用
                        }
                        catch (Exception)
                        {

                        }
                    }
                }
            }
            return cookieCollection;
        }
        private static CookieCollection GetCookies(string cookietxt, string host)
        {
            CookieCollection cookieCollection = new CookieCollection();
            CookieContainer cc = new CookieContainer();//调试用
            foreach (var cksplit in cookietxt.Split(','))
            {
                //(?![httponly,|httponly])(\S*?)=(.*?)(?:;|$)
                //MatchCollection mc = Regex.Matches(cksplit, "(.+?)=(.+?);", RegexOptions.Compiled);
                MatchCollection mc = Regex.Matches(cksplit, "(\\S*?)=(.*?)(?:;|$)", RegexOptions.Compiled);

                string cookies = string.Empty;//调试用

                foreach (Match item in mc)
                {
                    if (item.Groups[1].Value.Contains("expires") || item.Groups[1].Value.Contains("path") || item.Groups[1].Value.Contains("samesite"))
                    {
                        continue;
                    }
                    try
                    {
                        cookieCollection.Add(new Cookie(item.Groups[1].Value, item.Groups[2].Value, "/", host));
                        //调试用
                        cc.Add(new Cookie(item.Groups[1].Value, item.Groups[2].Value, "/", host));
                        cookies += cc.GetCookieHeader(new UriBuilder(host).Uri) + "|";
                        //调试用
                    }
                    catch (Exception)
                    {

                    }
                }
            }
            return cookieCollection;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值