[Help] html form login in C#

om3g4

Newbie
Joined
Mar 25, 2009
Messages
9
Reaction score
0
Code:
        string formUrl = "freerainbowtablesdotcom"; 
            string formParams = string.Format("username={0}&password={1}&login=1","om3g4","MYPASS");
            string cookieHeader;
            string pageSource;

            WebRequest req = WebRequest.Create(formUrl);
            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);
            }
            WebResponse resp = req.GetResponse();

            cookieHeader = resp.Headers["Set-cookie"];
           
            string getUrl = "freerainbowtablesdotcom";
            WebRequest getRequest = WebRequest.Create(getUrl);
            getRequest.Headers.Add("Cookie", cookieHeader);
            WebResponse getResponse = getRequest.GetResponse();
            using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
            {
                pageSource = sr.ReadToEnd();
            }

I would like to login freerainbowtablesdotcom programmatically.
I have this code, but something is wrong because, in pageSource I see the logged out html code.

What is the problem?
Any help is appreciated.
Thanks.
 
It might be because you're not using a CookieContainer.

See System.Net.CookieContainer on msdn
 
Looks like you're sending 2 separate requests? You should be logged in after the first request, not sure why you are sending another. You should build your cookies and headers in one request, sent it and then check the response. Also, like Chris said, you should be using a cookie container. You can just add the cookies from the response into your cookie container and pass that container around to your future requests.
 
You may login ok, but without the use of a cookie container your next request for the site will also require authentication. Follow Chris22's advice with the cookie container. Also, some secure sites require a valid "user-agent" within the header. Try adding this as well.
 
Back
Top