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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值