码迷,mamicode.com
首页 > 其他好文 > 详细

POST信息模拟登录获取页面内容

时间:2014-07-17 23:10:10      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:blog   http   使用   os   io   for   

最近项目里有一个是要模拟登录后,访问固定页面获取内容的要求,一开始用JQ AJAX好像不支持跨域请求。后使用.net中HttpWebRequest对象来获取。一开始访问总是无法在第二个页面正常访问,好像没通过登录验证,用postman模拟提交正常,后查询出原是忘记在第二次请求没把cookies关联上,关联上后请求正常。

            string wurl="";           
            string username="haxinet";
            string userpwd="haxinet";
            CookieContainer cookies = new CookieContainer();
            Encoding encode = System.Text.Encoding.UTF8;
            byte[] arrB = encode.GetBytes("user_name=" + username + "&user_passwd=" + userpwd + "&keepuser=1");        
            System.Net.HttpWebRequest myReq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(wurl);
            myReq.Method = "POST";
            myReq.ContentType = "application/x-www-form-urlencoded";
            myReq.ContentLength = arrB.Length;
            myReq.CookieContainer = cookies;
            Stream outStream = myReq.GetRequestStream();
            outStream.Write(arrB, 0, arrB.Length);
            outStream.Close();
            System.Net.WebResponse myResp = null;
            try
            {
                myResp = myReq.GetResponse();
            }
            catch (Exception e)
            {
              
            }
            Stream ReceiveStream = myResp.GetResponseStream();
            StreamReader readStream = new StreamReader(ReceiveStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            string str = null;
            while (count > 0)
            {
                str += new String(read, 0, count);
                count = readStream.Read(read, 0, 256);
            }
            readStream.Close();
            myResp.Close();

            string wuurl = "";
            HttpWebRequest myReq2 = (HttpWebRequest)HttpWebRequest.Create(wuurl);
            myReq2.Method = "GET";
            myReq2.CookieContainer = cookies;
            using (WebResponse wr = myReq2.GetResponse())
            {
                StreamReader reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);

                string result = reader.ReadToEnd();
                retStr = result;
            }    

  

POST信息模拟登录获取页面内容,布布扣,bubuko.com

POST信息模拟登录获取页面内容

标签:blog   http   使用   os   io   for   

原文地址:http://www.cnblogs.com/haxi/p/3851656.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!