实现网站的自动登录

首先打开网站,查看源文件,找到他的登录表单部分。现使用的表单如下:

                       
               
           
           
                       

以上__VIEWSTATE,textBoxRq,textBoxZh,textBoxMm,btnLogin五个字段缺一不可(当然若果少几个,代码编写更容易)。代码如下:
             string name = "519519";
            string pwd = "519519";
            string year = dateTimePicker1.Value.Year.ToString();、、dateTimePicker1为时间控件
            string month = dateTimePicker1.Value.Month.ToString();
            string day = dateTimePicker1.Value.Day.ToString();

            string login = "登陆";
            login = System.Web.HttpUtility.UrlEncode(login);//shiyong 网页地址格式的编码

            CookieContainer cc = new CookieContainer();//缓存

            string FormURL = urlstr;          //处理表单的绝对URL地址
            string FormData = "__VIEWSTATE=" + viestatevalue + "&textBoxRq=" + year + "-" + month + "-" + day + "&textBoxZh=" + name + "&textBoxMm=" + pwd + "&btnLogin=" + login;    //表单需要提交的参数,
                                                                                           //__VIEWSTATE值存在于网页源文件里用正则表达式抓取

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(FormData);//二进制格式编码

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FormURL);
            request.Method = "POST";    //数据提交方式
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)";
            //模拟一个UserAgent
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            request.CookieContainer = cc;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            cc.Add(response.Cookies);
            Stream stream = response.GetResponseStream();
            string WebContent = new StreamReader(stream, System.Text.Encoding.UTF8).ReadToEnd();
           
            HttpWebRequest Myrequest = (HttpWebRequest)WebRequest.Create(LaterURL);
            Myrequest.CookieContainer = cc;
            HttpWebResponse Myresponse = (HttpWebResponse)Myrequest.GetResponse();
            cc.Add(Myresponse.Cookies);
            Stream Mystream = Myresponse.GetResponseStream();
            string strResult = new StreamReader(Mystream, System.Text.Encoding.UTF8).ReadToEnd();
                                                                              //strResult为网页源文件字符串

你可能感兴趣的:(string,stream,input,login,正则表达式,encoding)