找传奇、传世资源到传世资源站!

C# 模拟请求HttpWebRequest 类源码

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

模拟请求,基于HttpWebRequest封装好的一个类,自动记下和发送Cookie,你只管调用方法就行了,很实用

        ///<summary>
        /// 使用post方式访问目标网页,返回stream二进制流
        ///</summary>
        public Stream PostAndGetStream(string targetURL, string formData, string contentType, string referer, bool allowAutoRedirect)
        {
            try
            {
                //数据编码
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(formData);

                //请求目标网页
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
                request.CookieContainer = cc;
                request.Method = "POST";    //使用post方式发送数据
                request.ContentType = contentType;
                request.Referer = referer;
                request.AllowAutoRedirect = allowAutoRedirect;
                request.ContentLength = data.Length;
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; EmbeddedWB 14.52 from: http://www.bsalsa.com/ EmbeddedWB 14.52; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";

                //模拟一个UserAgent
                Stream newStream = request.GetRequestStream();
                newStream.Write(data, 0, data.Length);
                newStream.Close();

                //获取网页响应结果
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                cc.Add(response.Cookies);
                responseUrl = response.ResponseUri.ToString();
                setCookie = response.Headers.Get("Set-Cookie");
                Stream stream = response.GetResponseStream();
                return stream;
            }
            catch (Exception ex)
            {
                string methodMsg = string.Format("HttpHelper/HttpHelper/public Stream PostAndGetStream({0}, {1}, {2}, {3}, {4})", targetURL, formData, contentType, referer, allowAutoRedirect);
                Common.WriteLog(string.Empty, ex.Message, methodMsg);
                return null;
            }
        }

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复