自己封装的HttpRequest,个人觉的比较HttpHelper好用

新年开篇,忙归忙,还是要写点什么,不然越来越懒,分享我写的HttpTooler

    public delegate void RequestCompleted(object sender, string html);
    public enum RequestType
    {
        WebRequest,
        HttpClient,
        WebClient
    }

    public class HttpTooler
    {
        private static byte[] postBuffer;
        //private HttpWebRequest request;
        private const string contentType = "application/x-www-form-urlencoded;charset=utf-8";
        private const string multipartType = "multipart/form-data; boundary=";
        private const string formBoundary = "----WebKitFormBoundary";
        private const string accept = "text/html, application/xhtml+xml, */*";
        private const string userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
        private const string cacheCtr = "Cache-Control";
        private const string noCache = "no-cache";

        private bool changeFlag;
        private string oldDomain;
        private string newDomain;

        public CookieContainer container;

        public RequestCompleted RequestCompleted
        {
            private get;
            set;
        }

        public HttpTooler()
        {
            container = new CookieContainer();
        }

        public HttpTooler(CookieContainer container)
        {
            this.container = container;
        }

        public void FixCookieDomain(string oldstr, string newstr)
        {
            changeFlag = true;
            oldDomain = oldstr;
            newDomain = newstr;
        }

        private void GetRequestHtml(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.KeepAlive = true;
            request.Timeout = 30000;
            request.ContentType = contentType;
            request.Accept = accept;
            request.UserAgent = userAgent;
            request.Headers.Add(cacheCtr, noCache);
            request.AllowAutoRedirect = false;
            request.CookieContainer = container;
            request.KeepAlive = true;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string html = string.Empty;
            using (Stream sw = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(sw))
                {
                    html = reader.ReadToEnd();
                }

                if (changeFlag) FixCookieDomain(response);
            }
            if (response != null) response.Close();

            DoCompleted(html);
        }

        public void GetHtml(RequestType type, string url)
        {
            if (type == RequestType.WebRequest)
            {
                GetRequestHtml(url);
            }
            else if (type == RequestType.WebClient)
            {
                GetWebClientHtml(url);
            }
            else
            {
                GetHttpClientHtml(url);
            }
        }

        private void GetWebClientHtml(string url)
        {
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
            byte[] data = wc.DownloadData(url);
            string html = Encoding.UTF8.GetString(data);

            DoCompleted(html);
        }

        private void GetHttpClientHtml(string url)
        {
            HttpClient hc = new HttpClient(container);
            hc.Credentials = CredentialCache.DefaultCredentials;
            byte[] data = hc.DownloadData(url);
            string html = Encoding.UTF8.GetString(data);

            DoCompleted(html);
        }

        public void PostData(string url, string param, string referer)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            if (string.IsNullOrEmpty(referer)) request.Referer = referer;
            request.KeepAlive = true;
            request.Timeout = 30000;
            request.ContentType = contentType;
            request.Accept = accept;
            request.UserAgent = userAgent;
            request.Headers.Add(cacheCtr, noCache);
            request.AllowAutoRedirect = false;
            request.CookieContainer = container;
            request.KeepAlive = true;
            byte[] buff = Encoding.UTF8.GetBytes(param);
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(buff, 0, buff.Length);
            reqStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string html = string.Empty;
            using (Stream sw = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(sw))
                {
                    html = reader.ReadToEnd();
                }

                string strcook = response.Headers["Set-Cookie"];

                if (changeFlag) FixCookieDomain(response);
            }
            if (response != null) response.Close();

            DoCompleted(html);
        }

        public void PostDataAsync(string url, string param)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.KeepAlive = true;
            request.Timeout = 30000;
            request.ContentType = contentType;
            request.CookieContainer = container;
            postBuffer = Encoding.UTF8.GetBytes(param);
            request.BeginGetRequestStream(new AsyncCallback(RequestStreamAsync), request);
        }

        private void DoCompleted(string rlt)
        {
            if (RequestCompleted != null)
            {
                RequestCompleted(this, rlt);
            }
        }

        private void RequestStreamAsync(IAsyncResult result)
        {
            HttpWebRequest request = (HttpWebRequest)result.AsyncState;
            Stream reqStream = request.EndGetRequestStream(result);
            reqStream.Write(postBuffer, 0, postBuffer.Length);
            reqStream.Close();
            request.BeginGetResponse(new AsyncCallback(ResponseAsync), request);
        }

        private void ResponseAsync(IAsyncResult result)
        {
            HttpWebRequest req = (HttpWebRequest)result.AsyncState;
            HttpWebResponse response = (HttpWebResponse)req.EndGetResponse(result);

            string html = string.Empty;
            using (Stream sw = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(sw))
                {
                    html = reader.ReadToEnd();
                }
            }
            if (response != null) response.Close();

            DoCompleted(html);
        }

        public void MultiPostData(string url, string referer, Dictionary<string, string> PostData)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.KeepAlive = true;
            request.Timeout = 30000;
            string boundary = formBoundary + DateTime.Now.Ticks.ToString("x");
            request.ContentType = string.Format("{0}{1}", multipartType, boundary);
            request.Accept = accept;
            request.UserAgent = userAgent;
            request.Headers.Add(cacheCtr, noCache);
            request.AllowAutoRedirect = false;
            request.CookieContainer = container;
            request.ServicePoint.Expect100Continue = false;
            if (referer != string.Empty) request.Referer = referer;

            byte[] buff = BuildMultiPostData(boundary, PostData);
            BinaryWriter bw = new BinaryWriter(request.GetRequestStream());
            bw.Write(buff);
            bw.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string html = string.Empty;
            using (Stream sw = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(sw))
                {
                    html = reader.ReadToEnd();
                }

                //第一次提交修改cookie
                if (changeFlag) { FixCookieDomain(response); }
            }
            if (response != null) response.Close();

            DoCompleted(html);
        }

        private byte[] BuildMultiPostData(string boundary, Dictionary<string, string> postData)
        {
            StringBuilder sb = new StringBuilder();

            // append access token.
            //sb.AppendLine("--" + boundary);
            //sb.Append(Environment.NewLine);

            // append form part.
            if (postData != null && postData.Count > 0)
            {
                foreach (KeyValuePair<string, string> HttpPostDataItem in postData)
                {
                    sb.AppendLine("--" + boundary);
                    sb.AppendLine(string.Format("Content-Disposition: form-data;name=\"{0}\"", HttpPostDataItem.Key));
                    sb.Append(Environment.NewLine);
                    sb.AppendLine(HttpPostDataItem.Value);
                }
            }

            MemoryStream ms = new MemoryStream();
            BinaryWriter bw = new BinaryWriter(ms);
            bw.Write(Encoding.UTF8.GetBytes(sb.ToString()));
            bw.Write(Encoding.UTF8.GetBytes(Environment.NewLine));
            bw.Write(Encoding.UTF8.GetBytes("--" + boundary + "--"));
            bw.Write(Encoding.UTF8.GetBytes(Environment.NewLine));
            ms.Flush();
            ms.Position = 0;

            byte[] result = ms.ToArray();

            bw.Close();

            return result;
        }

        private void FixCookieDomain(HttpWebResponse response)
        {
            string strCookie = response.Headers["Set-Cookie"];
            CookieCollection collect = GetCookiesFromReponseHead(strCookie, oldDomain);
            foreach (Cookie cook in collect)
            {
                Cookie ncook = new Cookie();
                ncook.Domain = oldDomain;
                ncook.Name = cook.Name;
                ncook.Value = cook.Value;
                Cookie pcook = FindCookie(newDomain, cook.Name);
                if (pcook == null)
                {
                    container.Add(ncook);
                }
                else
                {
                    pcook = ncook;
                }
            }

            changeFlag = false;
        }

        private CookieCollection GetCookiesFromReponseHead(string setCookieHeadStr, string defaultDomain)
        {
            CookieCollection cookies = new CookieCollection();
            if (!string.IsNullOrEmpty(setCookieHeadStr))
            {
                setCookieHeadStr = setCookieHeadStr.Replace("HttpOnly,", string.Empty).Replace("httponly", string.Empty);
                foreach (string str in setCookieHeadStr.Split(new string[] { "Path=/,", "path=/,", "path=/;", "Path=/;", "PATH=/;" }, StringSplitOptions.None))
                {
                    string cookieString = str.Trim();
                    if (cookieString.IndexOf(‘,‘) == 0)
                    {
                        cookieString = cookieString.Substring(1);
                    }
                    try
                    {
                        Cookie cookieFromString = GetCookieFromString(cookieString, defaultDomain);
                        if (cookieFromString != null)
                        {
                            cookies.Add(cookieFromString);
                        }
                    }
                    catch (Exception exception)
                    {
                        //LogManager.Error("GetCookiesFromReponseHead", exception);
                    }
                }
            }
            return cookies;
        }

        private static Cookie GetCookieFromString(string cookieString, string defaultDomain)
        {
            Cookie cookie = new Cookie();
            string[] strArray = cookieString.Split(new char[] { ‘;‘, ‘,‘ });
            int index = strArray[0].IndexOf("=");
            if (index == -1)
            {
                return null;
            }
            if (!strArray[0].ToLower().StartsWith("domain=") && !strArray[0].ToLower().StartsWith("expires="))
            {
                cookie.Name = strArray[0].Substring(0, index);
                cookie.Value = strArray[0].Substring(index + 1);
            }
            else
            {
                bool flag = false;
                if (strArray[0].ToLower().StartsWith("domain=") && strArray[0].Contains(","))
                {
                    strArray[0] = strArray[0].Substring(strArray[0].IndexOf(‘,‘) + 1);
                    index = strArray[0].IndexOf("=");
                    if (index > -1)
                    {
                        cookie.Name = strArray[0].Substring(0, index);
                        cookie.Value = strArray[0].Substring(index + 1);
                        flag = true;
                    }
                }
                if (!flag)
                {
                    for (int j = 1; j < strArray.Length; j++)
                    {
                        index = strArray[j].IndexOf("=");
                        if (index > 0)
                        {
                            string str = strArray[j].Substring(0, index);
                            if ((!str.ToLower().StartsWith("domain=") && !str.ToLower().StartsWith("expires=")) && !str.ToLower().StartsWith("version="))
                            {
                                string str2 = strArray[j].Substring(index + 1);
                                cookie.Name = str.Replace(",", "").Trim();
                                cookie.Value = str2;
                                flag = true;
                                break;
                            }
                        }
                    }
                }
                if (!flag)
                {
                    return null;
                }
            }
            Hashtable hashtable = new Hashtable();
            for (int i = 0; i < strArray.Length; i++)
            {
                if (!string.IsNullOrEmpty(strArray[i]))
                {
                    string str3 = strArray[i].Trim();
                    int length = str3.IndexOf("=");
                    if (length > 0)
                    {
                        string key = str3.Substring(0, length);
                        if (!hashtable.ContainsKey(key))
                        {
                            string str5 = str3.Substring(length + 1);
                            hashtable.Add(key, str5);
                        }
                    }
                }
            }
            foreach (object obj2 in hashtable.Keys)
            {
                if (obj2.ToString().ToLower() == "path")
                {
                    cookie.Path = hashtable[obj2].ToString();
                }
                else if (obj2.ToString().ToLower() == "expires")
                {
                    DateTime time;
                    if (DateTime.TryParse(hashtable[obj2].ToString(), out time))
                    {
                        cookie.Expires = time;
                    }
                }
                else if (obj2.ToString().ToLower() == "domain")
                {
                    if (hashtable[obj2].ToString().ToLower() == "koubei.com")
                    {
                        cookie.Domain = "." + hashtable[obj2].ToString();
                    }
                    else if (hashtable[obj2].ToString().ToLower() == "58.com")
                    {
                        cookie.Domain = "." + hashtable[obj2].ToString();
                    }
                    else
                    {
                        cookie.Domain = hashtable[obj2].ToString();
                    }
                }
                else if (obj2.ToString().ToLower() == "version")
                {
                    cookie.Version = int.Parse(hashtable[obj2].ToString());
                }
                else if (!(obj2.ToString().ToLower() == "max-age"))
                {
                    cookie.Expires = new DateTime(0x802, 1, 1);
                    cookie.Expired = false;
                }
            }
            if (cookie.Name == "")
            {
                return null;
            }
            if (cookie.Domain == "")
            {
                cookie.Domain = defaultDomain;
            }
            return cookie;
        }

        private Cookie FindCookie(string Url, string name)
        {
            if (Url.Substring(0, 5).ToLower() != "http:")
            {
                Url += "http://" + Url;
            }
            CookieCollection cookies = container.GetCookies(new Uri(Url));
            if (cookies != null)
            {
                foreach (Cookie cookie in cookies)
                {
                    if (cookie.Name == name)
                    {
                        return cookie;
                    }
                }
            }
            return null;
        }
    }

    class HttpClient : WebClient
    {
        // Cookie 容器
        private CookieContainer cookieContainer;

        /**/
        /// <summary>
        /// 创建一个新的 WebClient 实例。
        /// </summary>
        public HttpClient()
        {
            this.cookieContainer = new CookieContainer();
        }

        /**/
        /// <summary>
        /// 创建一个新的 WebClient 实例。
        /// </summary>
        /// <param name="cookie">Cookie 容器</param>
        public HttpClient(CookieContainer cookies)
        {
            this.cookieContainer = cookies;
        }

        /**/
        /// <summary>
        /// Cookie 容器
        /// </summary>
        public CookieContainer Cookies
        {
            get { return this.cookieContainer; }
            set { this.cookieContainer = value; }
        }

        /**/
        /// <summary>
        /// 返回带有 Cookie 的 HttpWebRequest。
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest request = base.GetWebRequest(address);
            if (request is HttpWebRequest)
            {
                HttpWebRequest httpRequest = request as HttpWebRequest;
                httpRequest.CookieContainer = cookieContainer;
            }
            return request;
        }
    }

有WebClient DownloadData,比较大的数据页面可以使用它下载,比Request请求快多了。

支持Cookie修改,域名重定向,富媒体表单,异步请求,事件完成。做个58同城登录分分钟的事情

HttpTooler tooler = new HttpTooler();
tooler.RequestCompleted = OnRequestCompleted;
tooler.GetHtml(RequestType.WebRequest, "www.58.com");

void OnRequestCompleted(object sender, string html)
{
        //参数html 就是返回的结果
        // do you want...
}

that‘s all enjoy...

时间: 2024-10-12 01:37:41

自己封装的HttpRequest,个人觉的比较HttpHelper好用的相关文章

Drf04 / drf request请求对象封装、版本、认证、权限

目录 Drf04 / drf request请求对象封装.版本.认证.权限 回顾和补充 今日详细 1.请求的封装 2.版本 3.认证(面试) 4.权限 Drf04 / drf request请求对象封装.版本.认证.权限 回顾和补充 restful规范 1. 建议用https代替http 2. 在URL中体现api,添加api标识 https://www.cnblogs.com/xwgblog/p/11812244.html # 错误 https://www.cnblogs.com/api/xw

ASP.NET平台下从浏览器地址栏输入之后发生的事

浏览器一般内嵌两个模块: Socket通信模块 → 浏览器将地址栏的数据及其他的数据放入http协议的请求头文件中,Socket将此http请求数据发送到远程服务器端 浏览器引擎渲染模块 → 浏览器接受从服务器返回的http响应头数据以及用户请求的数据渲染成用户所见的界面 ASP.NET开发人员和HttpApplication,HttpContext,HttpRequest,HttpResponse这四个类应该是老熟人了,而ASP.NET事件管道也是ASP.NET程序员耳熟能详的,就笔者自己而言

第三篇:白话tornado源码之请求来了

上一篇<白话tornado源码之待请求阶段>中介绍了tornado框架在客户端请求之前所做的准备(下图1.2部分),本质上就是创建了一个socket服务端,并进行了IP和端口的绑定,但是未执行 socket的accept方法,也就是未获取客户端请求信息. 概述 本篇就来详细介绍tornado服务器(socket服务端)是如何接收用户请求 数据以及如果根据用户请求的URL处理并返回数据,也就是上图的3系列所有步骤,如上图[start]是一个死循环,其中利用epoll监听服务端 socket句柄,

django-request对象

HTTP 应用的信息是通过 请求报文 和 响应报文 传递的,关于更多的相关知识,可以阅读<HTTP权威指南>获得. 其中 请求报文 由客户端发送,其中包含和许多的信息,而 django 将这些信息封装成了 HttpRequest 对象,该对象由 HttpRequest 类创建.每一个请求都会生成一个 HttpRequest 对象,django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 request 参数承接这个对象. 例如: def index(request): ..

初识servlet

servlet是一种服务器端的java应用程序,具有独立于平台和协议的特性,可以生成动态的web页面,她担当客户请求与服务器响应的中间层,servlet是位于web服务器内部的服务器端的java应用程序,与传统的从命令行启动的java应用程序不同,servlet由web服务器进行加载,该web服务器必须包含支持servlet的java虚拟机,Servlet(Server Applet),全称Java Servlet,未有中文译文.是用Java编写的服务器端程序.其主要功能在于交互式地浏览和修改数

一个CURL

CURL curl是利用url语法规则来传输文件,数据的工具,主要实现和服务器中网页,资源传输的工具.这里有一个关于感冒还没好的段子. 1.去phpini开启curl扩展,重启阿帕奇或者配置环境变量或者重启电脑,严重点需要重装,你懂得.curl模拟get请求,可以进行采集,程序员的事情这么能叫偷呢,如果想采集https的资源,需要进行跳过证书验证.2.curl模拟post请求,post主要是向服务器提交一些数据 3.封装一个httprequest的类直接调用,通过传数组判定是get还是post

django的views里面的request对象详解大全

简介 HTTP 应用的信息是通过 请求报文 和 响应报文 传递的,关于更多的相关知识,可以阅读<HTTP权威指南>获得. 其中 请求报文 由客户端发送,其中包含和许多的信息,而 django 将这些信息封装成了 HttpRequest 对象,该对象由 HttpRequest 类创建.每一个请求都会生成一个 HttpRequest 对象,django会将这个对象自动传递给响应的视图函数,一般视图函数约定俗成地使用 request 参数承接这个对象. 例如: def index(request):

Python框架之Tornado(三)请求

概述 本篇就来详细介绍tornado服务器(socket服务端)是如何接收用户请求数据以及如果根据用户请求的URL处理并返回数据,也就是上图的3系列所有步骤,如上图[start]是一个死循环,其中利用epoll监听服务端socket句柄,一旦客户端发送请求,则立即调用HttpServer对象的_handle_events方法来进行请求的处理. 对于整个3系列按照功能可以划分为四大部分: 获取用户请求数据(上图3.4) 根据用户请求URL进行路由匹配,从而使得某个方法处理具体的请求(上图3.5-3

Django 1

Django 1.10文档中文版Part1 本文是博主翻译的Django1.10版本官方文档的第一部分,如时间充裕,争取一直翻译下去,经验不足,或有错漏,敬请指正.另外对于公开文档进行翻译的版权问题不是很清楚,如有侵权请联系我! 目录 第一章.Django1.10文档组成结构1.1 获取帮助1.2 文档的组织形式1.3 第一步1.4 模型层1.5 视图层1.6 模板层1.7 表单1.8 开发流程1.9 admin站点1.10 安全性1.11 国际化和本地化1.12 性能和优化1.13 Pytho