首页 > 学院 > 开发设计 > 正文

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

2019-11-17 01:38:56
字体:
来源:转载
供稿:网友

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

最近项目里有一个是要模拟登录后,访问固定页面获取内容的要求,一开始用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;            }    

  


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表