How to pull data from web after login using HttpWe

2019-08-24 14:37发布

问题:

I am trying to pull data from a login so I would be able to verify that the login succeeds.

How do I use the HttpWebRequest to pull the content of the page so I could use it to verify the login is good.

Since every login return status code 200 if the login is correct and incorrect it makes it harder to verify success login.

private int[] LoginCheck(string TargetWebApp)
        {
            int[] result = new int[2];
            var watch = System.Diagnostics.Stopwatch.StartNew();
            try
            {


                string formUrl = "https://someweb/user/login/default";
                string formParams = string.Format("email={0}&password={1}&submit=Login", "someuser@somedomain.com", "somepassword");
                string cookieHeader;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                req.ContentType = "application/x-www-form-urlencoded";
                req.Method = "POST";
                byte[] bytes = Encoding.ASCII.GetBytes(formParams);
                req.ContentLength = bytes.Length;
                using (Stream os = req.GetRequestStream())
                {
                    os.Write(bytes, 0, bytes.Length);
                }
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

                var elapsedMs = watch.ElapsedMilliseconds;
                watch.Stop();
                var isInvalidAccess = resp.StatusCode == HttpStatusCode.Unauthorized;
                Console.WriteLine("Login to something succeed in {0} Milliseconds", elapsedMs);
                cookieHeader = resp.Headers["Set-cookie"];
                result[0] = 1;
                result[1] = (int)elapsedMs;

            }
            catch (Exception e)
            {
                //Any exception will return false.
                Console.WriteLine(e.Message);
                result[0] = 0;
                result[1] = 0;
            }

            return result;
        }