net 網站自動登入

來源:互聯網
上載者:User

樓主,根據你的意思,我自己用代碼寫了一個CSDN的登入器,發給你參考一下,下面說說具體的思路.

首先,我們先定義一些變數:
C# code

        private const string NET_SESSIONID= "ASP.NET_SessionId=";
        private const string CLIENTKEY = "ClientKey=";

        string aspcookie = "";
        private string html = "";
        private string sessionId = "";
        private string clientKey = "";
        private string viewState = "";

一、利用HttpWebRequest擷取CSDN的登入資訊,如ASP.NET_SessionId、ClientKey、__VIEWSTATE。這步可以放在Login_Load中,下面是代碼:
C# code

        private void Login_Load(object sender, EventArgs e)
        {
            HttpWebRequest request = WebRequest.Create("http://passport.csdn.net/UserLogin.aspx") as HttpWebRequest;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Accept = "*/*";
            request.Referer = "http://passport.csdn.net/UserLogin.aspx";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";
            request.Method = "GET";
            request.KeepAlive = true;
            request.Headers.Set("Accept-Language", "zh-CN");
            request.Headers.Set("Accept-Encoding", "gzip, deflate");

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            System.IO.Stream responseStream = response.GetResponseStream();
            System.IO.StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            html = reader.ReadToEnd();

            string viewStateFlag = "id=\"__VIEWSTATE\" value=\"";
            int i = html.IndexOf(viewStateFlag) + viewStateFlag.Length;
            int j = html.IndexOf("\"", i);
            viewState = html.Substring(i, j - i);

            aspcookie = response.Headers.Get("Set-Cookie");
            sessionId = GetSessionId();
            clientKey = GetClientKey();
            // 擷取圖片驗證碼
            GetCode();
        }
         /// <summary>
        /// 擷取ClientKey
        /// </summary>
        /// <returns></returns>
        private string GetClientKey()
        {
            // 這個僅僅是用來擷取ClientKey值的長度
            string id = "bb32434c-3bb3-4e44-92c3-8952f631ca87";
            int index = aspcookie.IndexOf(CLIENTKEY) + CLIENTKEY.Length;
            String str = aspcookie.Substring(index, id.Length);
            return str;
        }

        /// <summary>
        /// 擷取ASP.NET_SessionId=
        /// </summary>
        /// <returns></returns>
        private string GetSessionId()
        {
            string id = "5mhl0tvbw5shlpnhxgwnck45";
            int index = aspcookie.IndexOf(NET_SESSIONID) + NET_SESSIONID.Length;
            String str = aspcookie.Substring(index, id.Length);
            return str;
        }

     

二、擷取圖片驗證碼,在這一步中需要注意的是,因為我們用的是另外一個HttpWebRequest去擷取,所以為了保持擷取的驗證碼與登入頁面的Session一致,我們需要把Session等資訊放入Header中去,下面是代碼:
C# code

/// <summary>
        /// 產生新的驗證碼
        /// </summary>
        private void GetCode()
        {
            try
            {
                CookieCollection cookies = new CookieCollection();
                cookies.Add(new Cookie("ASP.NET_SessionId",sessionId));
                cookies.Add(new Cookie("ClientKey",clientKey));

                HttpWebRequest httpWebRequest;
                HttpWebResponse webResponse;
                byte[] byteRequest = { };
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://passport.csdn.net/ShowExPwd.aspx");
                CookieContainer co = new CookieContainer();
                co.Add(new Uri("http://passport.csdn.net"), cookies);
                httpWebRequest.CookieContainer = co;
                httpWebRequest.Accept = "*/*";
                httpWebRequest.Referer = "http://passport.csdn.net/UserLogin.aspx";
                httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";
                httpWebRequest.Method = "GET";
                httpWebRequest.Headers.Set("Accept-Encoding", "gzip, deflate");
                httpWebRequest.Headers.Set("Accept-Language", "zh-CN");
                httpWebRequest.KeepAlive = true;

                webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = webResponse.GetResponseStream();
                Image original = Image.FromStream(responseStream);
                Bitmap bitMap = new Bitmap(original);
                this.pictureBox1.Image = bitMap;
                responseStream.Close();
            }
            catch (Exception exception)
            {
                MessageBox.Show("ERROR:" + exception.Message);
            }
        }

三、最後一步是登入事件,登入很簡單,把相關的資訊放入請求資料中就行了。
C# code

private void btnLogin_Click(object sender, EventArgs e)
        {
            HttpWebRequest httpWebRequest;
            HttpWebResponse webResponse;

            string randnum = txtRandnum.Text;
            string password = txtPassword.Text;
            string loginname = txtUserName.Text;

            string postData = "ctl00$CPH_Content$tb_LoginNameOrLoginEmail={0}&ctl00$CPH_Content$tb_Password={1}&ctl00$CPH_Content$tb_ExPwd={2}&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE={3}&ClientKey={4}&from={5}&MailParameters=&PrePage=&ctl00$CPH_Content$Image_Login.x=46&ctl00$CPH_Content$Image_Login.y=9";
            postData = string.Format(postData, System.Web.HttpUtility.UrlEncode(loginname),System.Web.HttpUtility.UrlEncode(password),System.Web.HttpUtility.UrlEncode(randnum), System.Web.HttpUtility.UrlEncode(viewState), clientKey, System.Web.HttpUtility.UrlEncode("http://hi.csdn.net/"));
            byte[] byteRequest = Encoding.UTF8.GetBytes(postData);

            CookieCollection cookies = new CookieCollection();
            cookies.Add(new Cookie("ASP.NET_SessionId", sessionId));
            cookies.Add(new Cookie("ClientKey", clientKey));
            cookies.Add(new Cookie("UN",loginname));

            httpWebRequest = (HttpWebRequest)HttpWebRequest.Create("http://passport.csdn.net/UserLogin.aspx");
            CookieContainer co = new CookieContainer();
            co.Add(new Uri("http://passport.csdn.net"), cookies);
            httpWebRequest.CookieContainer = co;
            httpWebRequest.ContentType = "application/x-www-form-urlencoded";
            httpWebRequest.Accept = "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, */*";
            httpWebRequest.Referer = "http://passport.csdn.net/UserLogin.aspx";
            httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)";
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Headers.Set("Cache-Control", "no-cache");
            httpWebRequest.Headers.Set("Accept-Encoding", "gzip, deflate");
            httpWebRequest.Headers.Set("Accept-Language", "zh-CN");

            httpWebRequest.ContentLength = byteRequest.Length;
            Stream stream;
            stream = httpWebRequest.GetRequestStream();
            stream.Write(byteRequest, 0, byteRequest.Length);
            stream.Close();
            webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            System.IO.Stream responseStream = webResponse.GetResponseStream();

            String header = webResponse.Headers.ToString();
            Stream getStream = webResponse.GetResponseStream();
            long contentLength = webResponse.ContentLength;

            byte[] outBytes = new byte[contentLength];
            outBytes = ReadFully(getStream);
            getStream.Close();

            getStream = new MemoryStream(outBytes);
            StreamReader streamReader = new StreamReader(getStream, Encoding.UTF8);
            string getString = streamReader.ReadToEnd();
            streamReader.Close();
            getStream.Close();

        }

        static byte[] ReadFully(Stream stream)
        {
            byte[] buffer = new byte[128];
            using (MemoryStream ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }

其中,在如果把資料以及需要把哪些資料Post到伺服器中花費了不少時間,後來利用HttpAnalyzer來抓取瀏覽器中登入的資料包與WinForm登入的資料包進行了對比,才找出問題所在。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.