根据已知用户名和密码用HttpWebRequest获得的CookieContainer后,怎么能做出效果相当于在网站上真正登陆一样,以便打开或跳转到需要登陆的网页进行浏览!

解决方案 »

  1.   

       下面是我取CookieContainer的方法...CookieContainer取出来了,也可以用HttpWebResponse取得登录后想要的数据,但是不能直接跳转进入网站.
     private  string PostWebRequest()        
            {
                           CookieContainer cc = new CookieContainer();
                            string postData = "logintype=uid&u=xxxx&psw=xxxx&product=mail&%B5%C7%C2%BC=%B5%C7+%C2%BC";
                       byte[] byteArray = Encoding.UTF8.GetBytes(postData); // 转化            HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create("http://mail.sina.com.cn/cgi-bin/login.php");
                webRequest2.CookieContainer = cc;
                webRequest2.AllowAutoRedirect = true;
                webRequest2.Method = "POST";
                webRequest2.ContentType = "application/x-www-form-urlencoded";
                webRequest2.ContentLength = byteArray.Length;
                Stream newStream = webRequest2.GetRequestStream();
                // Send the data.
                newStream.Write(byteArray, 0, byteArray.Length);    //写入参数
                  newStream.Close();           HttpWebResponse response2 = (HttpWebResponse)webRequest2.GetResponse();
               response2.Cookies = cc.GetCookies(webRequest2.RequestUri);
               string a = "";
               foreach (Cookie i in webRequest2.CookieContainer.GetCookies(new Uri("http://mail.sina.com.cn/cgi-bin/login.php")))
               {
                   a += i.ToString() + ";";
               } 
                cc.Add(response2.Cookies);   
               StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.GetEncoding("UTF-8"));           
                string str =  sr2.ReadToEnd();
               
                return str;        
             }