0

我一直在尝试制作一个程序,该程序将使用特定详细信息登录用户,然后在使用正则表达式登录后从下一页获取并显示一个值。我已经尝试保存 cookie 等,以便我能够跨功能保持登录状态,但它似乎不起作用。这是我的代码:

public void initiateCredits(string user, string pass)
    {
        WebBrowser wb1 = new WebBrowser();
        wb1.Navigate("http://site.com/login.php");
        string webData = wb1.DocumentText;
        Regex check = new Regex("(?<=You have)(.*)(?=credits)", RegexOptions.Singleline);
        bool checkmatch = check.IsMatch(webData);
        if (checkmatch == true)
        {
            return;
        }
        else
        {
            ServicePointManager.Expect100Continue = false;


            string url = "http://site.com/login.php";
            string pass_d = Base64.decode(pass);
            string postData = String.Format("username=" + user + "&password=" + pass_d);
            //byte[] Post = Encoding.UTF8.GetBytes(postData);
            //WebClient wc = new WebClient();

            WebRequest req = WebRequest.Create(url);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            byte[] bytes = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = bytes.Length;
            using (Stream os = req.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }
            WebResponse resp = req.GetResponse();
            cookieHeader = resp.Headers["Set-cookie"];

            //byte[] response = wc.UploadValues(url, new NameValueCollection()
   //{
       //{ "username", user },
       //{ "password", pass_d }
   //});
            creditlogin = true;

            //string AdditionalHeaders = "Content-Type: application/x-www-form-urlencoded";
            //wb.Navigate(url, null, Post, AdditionalHeaders);
        }

然后我尝试通过以下方式实际获得学分:

public string getCredits()
    {
        if (creditlogin == true)
        {
            string pageSource;
            string getUrl = "http://site.com/login.php";
            WebRequest getRequest = WebRequest.Create(getUrl);
            getRequest.Headers.Add("Cookie", cookieHeader);
            WebResponse getResponse = getRequest.GetResponse();
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                pageSource = sr.ReadToEnd();
            }

            //System.Net.WebClient wc2 = new System.Net.WebClient();
            //string webData = wc2.DownloadString("http://beta.myvmk.com/security_check.php");
            Regex r = new Regex("(?<=You have)(.*)(?=credits)", RegexOptions.Singleline);
            Match credits = r.Match(pageSource);
            return credits.ToString();
        }
        else
        {
            return "err";
        }

    }

我真的被困了好几天了,有人可以帮忙吗?谢谢!目前我只是返回一个“错误”,所以我假设这意味着initialCredits 无法正常工作。

4

0 回答 0