WebBrowser通过cookie自动登录网站

企业内网有很多网站,每个网站都要登录帐号密码,为了管理方便自己开发了一个winform的工具,用来登录这些业务网站。

需要注册com组件。

    [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

通过webrequest请求获取登录的cookie。

 private bool RequestIsOk(string url, string postData,ref string cookie)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.AllowAutoRedirect = false;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1;)";
            request.Headers.Add("Accept-Encoding", "gzip, deflate");
            request.ContentType = "application/x-www-form-urlencoded";
            if (!string.IsNullOrEmpty(postData))
            {
                byte[] bytes = Encoding.UTF8.GetBytes(postData);
                request.ContentLength = bytes.Length;
                // 必须先设置ContentLength,才能打开GetRequestStream
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
            }
            else
                request.ContentLength = 0;// POST时,必须设置ContentLength属性
            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                var s = response.Headers;
                foreach (var key in s.Keys)
                {
                    if ((string) key == "Set-Cookie")
                    {
                        cookie = s["Set-Cookie"];
                    }
                }
                
                return true;
            }
            catch (WebException webExp)
            {
                return false;
            }
        }

调用代码。

 string cookieStr = "";
            string postdata = "login_username=aaa&login_password=123";//需要提交的数据(我这里是模拟的参数)
            RequestIsOk("登录的验证地址", postdata, ref cookieStr);
               
                wb.Dock = DockStyle.Fill; //WebBrowser wb = new WebBrowser();
                string[] cookstr = cookieStr.Split(';');
                foreach (string str in cookstr)
                {
                    string[] cookieNameValue = str.Split('=');
                    InternetSetCookie(tab.Urls[i], cookieNameValue[0].Trim(), cookieNameValue[1].Trim());
                }
                wb.Navigate(“需要访问的地址”);
posted @ 2012-11-16 11:00  魂斗罗II  阅读(566)  评论(0编辑  收藏  举报