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;
            }
        }
    }

哈哈,这下爽了

时间: 2024-08-22 06:29:39

WebRequestHelper的相关文章

C#使用Http的Post方式请求webservice

webservice是以前比较流行的跨系统.跨语言.跨平台的数据交互技术.最近工作中调用Java作为服务端开放的webser,我是通过VS205生成webservice工具类的方式进行接口调用的.用这种方式的理由是对自身的工程项目影响较小,系统生成一个工具了,只需要将此工具类放置对应的目录下并包含在项目中即可.这种方式看似很好,但是我最近的这个项目出现一个奇怪的问题,就是用webservice工具类调用接口返回值居然是null,用SoapUI测试却是正常返回了数据,于是我使用Postman测试了

请求WebApi的几种方式

目前所了解的请求WebAPI的方式有通过后台访问api 和通过js 直接访问api接口 首先介绍下通过后台访问api的方法,可以使用HttpClient的方式也可以使用WebRequest的方式 1.HttpClient的方式 (1)Get请求 string url = "http://10.1.1.1:8080/"; public ActionResult GetAll() { HttpClient client = new HttpClient(); client.BaseAddr

C# v3微信 access token 过期处理的问题

1 //记录access token 申请时的时间 2 private static DateTime GetAccessToken_Time; 3 /// <summary> 4 /// 过期时间为7200秒 5 /// </summary> 6 private static int Expires_Period = 7200;   private static string mAccessToken; 7 /// <summary> 8 /// 获取access t

测试扫描支付功能

1 private Dictionary<string, object> WeixinPayTest(string body, string attach, string out_trade_no, int total_fee, long product_id) 2 { 3 string url = "http://spdbapi.ulopay.com/pay/unifiedorder";//浦发银行测试获取支付二维码地址 4 Dictionary<string, o

通过HTTP请求WEBAPI的方式

平时工作中长期需要用到通过HTTP调用API进行数据获取以及文件上传下载(C#,JAVA...都会用到).这里获取的是包括网页的所有信息.如果单纯需要某些数据内容.可以自己构造函数甄别抠除出来!一般的做法是根据源码的格式,用正则来过滤出你需要的内容部分. C#中的调用: 方式一:webclient和httpclient 方式二:WebRequest和webresponse 方式三:通过js 直接访问api接口,页面通过jquery调用 方式四:WebBrowser 1.webclient和htt