我是靠谱客的博主 陶醉煎饼,最近开发中收集的这篇文章主要介绍WebRequestHelper老是浪费时间写这个类,干脆记录在博客里:,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

老是浪费时间写这个类,干脆记录在博客里:

 

public class WebRequestHelper
    {
        #region Post
        public static CookieContainer GetCookieContainer(string url, object paras = null)
        {
            CookieContainer mycookiecontainer = new CookieContainer();
            try
            {
                string outdata = "";

                HttpWebRequest myhttpwebrequest = (HttpWebRequest)WebRequest.Create(url);
                myhttpwebrequest.Method = "post";
                myhttpwebrequest.CookieContainer = mycookiecontainer;
                myhttpwebrequest.ContentType = "application/x-www-form-urlencoded";
                myhttpwebrequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36";

                byte[] payload = null;
                string formData = GetFormData(paras);
                if (!string.IsNullOrEmpty(formData))
                {
                    payload = System.Text.Encoding.UTF8.GetBytes(formData);
                    myhttpwebrequest.ContentLength = payload.Length;
                }

                Stream myrequeststream = myhttpwebrequest.GetRequestStream();
                StreamWriter mystreamwriter = new StreamWriter(myrequeststream, Encoding.GetEncoding("gb2312"));
                if (payload != null && payload.Length > 0)
                {
                    //将请求参数写入流
                    myrequeststream.Write(payload, 0, payload.Length);
                }
                mystreamwriter.Close();
                myrequeststream.Close();

                HttpWebResponse myhttpwebresponse = (HttpWebResponse)myhttpwebrequest.GetResponse();
                myhttpwebresponse.Cookies = mycookiecontainer.GetCookies(myhttpwebrequest.RequestUri);

                Stream myresponsestream = myhttpwebresponse.GetResponseStream();
                StreamReader mystreamreader = new StreamReader(myresponsestream, Encoding.GetEncoding("gb2312"));
                outdata = mystreamreader.ReadToEnd();
                mystreamreader.Close();
                myresponsestream.Close();
            }
            catch (Exception msg)
            {
                mycookiecontainer = null;
            }
            return mycookiecontainer;

        }

        public static string HttpPost(string url, CookieContainer mycookiecontainer, object paras = null)
        {
            return HttpPost(url, Encoding.UTF8, mycookiecontainer, paras);
        }
        public static string HttpPost(string url, Encoding encoding, CookieContainer mycookiecontainer, object paras = null)
        {
            string responseText = "";
            HttpWebRequest request;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "post";
                request.CookieContainer = mycookiecontainer;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36";
                request.ServicePoint.Expect100Continue = false;

                byte[] payload = null;
                string formData = GetFormData(paras);
                if (!string.IsNullOrEmpty(formData))
                {
                    payload = System.Text.Encoding.UTF8.GetBytes(formData);
                    request.ContentLength = payload.Length;
                }

                Stream writer = request.GetRequestStream();
                if (payload != null && payload.Length > 0)
                {
                    writer.Write(payload, 0, payload.Length);
                }
                writer.Close();


                HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
                StreamReader myreader = new StreamReader(response.GetResponseStream(), encoding);
                responseText = myreader.ReadToEnd();
                myreader.Close();
            }
            catch (Exception ex)
            {
                responseText = ex.Message;
            }
            return responseText;
        }
        #endregion

        #region Get
        public static string HttpGet(string url, CookieContainer cookiecontainer, out HttpStatusCode status)
        {
            return HttpGet(url, cookiecontainer, Encoding.GetEncoding("GB2312"), out status);
        }
        public static string HttpGet(string url, CookieContainer cookiecontainer, Encoding encoding, out HttpStatusCode status)
        {
            status = HttpStatusCode.NotFound;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
                myReq.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705";
                myReq.Accept = "*/*";
                myReq.KeepAlive = true;
                myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
                if (cookiecontainer != null)
                {
                    myReq.CookieContainer = cookiecontainer;
                }

                HttpWebResponse myResponse = (HttpWebResponse)myReq.GetResponse();
                status = myResponse.StatusCode;
                Stream receviceStream = myResponse.GetResponseStream();
                StreamReader readerOfStream = new StreamReader(receviceStream, encoding);
                string strHTML = readerOfStream.ReadToEnd();

                readerOfStream.Close();
                receviceStream.Close();
                myResponse.Close();
                return strHTML;
            }
            catch (Exception msg)
            {
                return msg.Message;
            }
        }

        public static string HttpGet(string url,NameValueCollection nvc,CookieContainer cookiecontainer, Encoding encoding, out HttpStatusCode status)
        {
            status = HttpStatusCode.NotFound;
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
                myReq.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705";
                myReq.Accept = "*/*";
                myReq.KeepAlive = true;
                foreach (string key in nvc)
                {
                    myReq.Headers.Add(key, nvc[key]);
                }
                myReq.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");

                HttpWebResponse myResponse = (HttpWebResponse)myReq.GetResponse();
                status = myResponse.StatusCode;
                Stream receviceStream = myResponse.GetResponseStream();
                StreamReader readerOfStream = new StreamReader(receviceStream, encoding);
                string strHTML = readerOfStream.ReadToEnd();

                readerOfStream.Close();
                receviceStream.Close();
                myResponse.Close();
                return strHTML;
            }
            catch (Exception msg)
            {
                return msg.Message;
            }
        }
        #endregion

        #region cookieContainer
        public static string GetCookie(string cookieName, CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();
            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
                System.Reflection.BindingFlags.Instance, null, cc, new object[] { });
            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                    | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c1 in colCookies) lstCookies.Add(c1);
            }
            var model = lstCookies.Find(p => p.Name.ToLower() == cookieName.ToLower());
            if (model != null)
            {
                return model.Value;
            }
            return string.Empty;
        }
        public static List<Cookie> GetAllCookies(CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();

            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
                System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                    | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies) lstCookies.Add(c);
            }
            return lstCookies;
        }

        public static void AddCookie(string cookie, CookieContainer cc, string domain)
        {
            string[] tempCookies = cookie.Split(';');
            string tempCookie = null;
            int Equallength = 0;//  =的位置 
            string cookieKey = null;
            string cookieValue = null;
            //qg.gome.com.cn  cookie 
            for (int i = 0; i < tempCookies.Length; i++)
            {
                if (!string.IsNullOrEmpty(tempCookies[i]))
                {
                    tempCookie = tempCookies[i];
                    Equallength = tempCookie.IndexOf("=");
                    if (Equallength != -1)       //有可能cookie 无=,就直接一个cookiename;比如:a=3;ck;abc=; 
                    {
                        cookieKey = tempCookie.Substring(0, Equallength).Trim();
                        //cookie=

                        if (Equallength == tempCookie.Length - 1)    //这种是等号后面无值,如:abc=; 
                        {
                            cookieValue = "";
                        }
                        else
                        {
                            cookieValue = tempCookie.Substring(Equallength + 1, tempCookie.Length - Equallength - 1).Trim();
                        }
                    }
                    else
                    {
                        cookieKey = tempCookie.Trim();
                        cookieValue = "";
                    }
                    cc.Add(new Cookie(cookieKey, cookieValue, "", domain));
                }
            }
        }
        #endregion
        private static string GetFormData(object paras)
        {
            StringBuilder formData = new StringBuilder();
            if (paras != null)
            {
                Type t = paras.GetType();
                foreach (PropertyInfo pi in t.GetProperties())
                {
                    string name = pi.Name;
                    object val = pi.GetValue(paras, null);

                    if (formData.ToString() == "")
                    {
                        formData.Append(name + "=" + val);
                    }
                    else
                    {
                        formData.Append("&" + name + "=" + val);
                    }
                }
            }
            return formData.ToString();
        }
        private static void SetHeaderValue(WebHeaderCollection header, string name, string value)
        {
            var property = typeof(WebHeaderCollection).GetProperty("InnerCollection",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            if (property != null)
            {
                var collection = property.GetValue(header, null) as NameValueCollection;
                collection[name] = value;
            }
        }
    }

 

哈哈,这下爽了

 

转载于:https://www.cnblogs.com/dengshaojun/p/5691317.html

最后

以上就是陶醉煎饼为你收集整理的WebRequestHelper老是浪费时间写这个类,干脆记录在博客里:的全部内容,希望文章能够帮你解决WebRequestHelper老是浪费时间写这个类,干脆记录在博客里:所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部