Question httpWebrequest login

Zexor

Well-known member
Joined
Nov 28, 2008
Messages
520
Programming Experience
3-5
how do i use httpwebrequest to login to a website? With WebBrowser control i was using this on another site.

VB.NET:
            WebBrowser1.Document.All("username").InnerText = name
            WebBrowser1.Document.All("password").InnerText = pass
            WebBrowser1.Document.All("loginsubmit").InvokeMember("click")

but this other site's login button doesnt seem to have a name and httpwebreuqest seems to load the page faster. But how to login so i can get the logged in version of the webdoc? I have this so far but how do you determine the postData ? Is it from the form action?
<form action="http://www.test.com/login.php?do=login" method="post" onsubmit="md5hash(password, md5password, md5password_utf, 0)">
VB.NET:
       Dim postData As String
        postData = "username=name&password=pass"
        Dim request As Net.HttpWebRequest
        Dim response As Net.HttpWebResponse
        request = CType(Net.WebRequest.Create("http://www.test.com/login.php?do=login"), Net.HttpWebRequest)
        request.ContentType = "application/x-www-form-urlencoded"
        request.ContentLength = postData.Length
        request.Method = "POST"
        request.AllowAutoRedirect = False


        Dim requestStream As IO.Stream = request.GetRequestStream()
        Dim postBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(postData)
        requestStream.Write(postBytes, 0, postBytes.Length)
        requestStream.Close()


        response = CType(request.GetResponse(), Net.HttpWebResponse)
 
You don't have to explicitly login via the login page. You simply provide the appropriate credentials, i.e. user name and password, when you request data. The WebRequest has a Credentials property, to which you assign an ICredential object used to identify the user making the request.

If you're making multiple requests then you could just provide credentials each time but they won't be performed in the same session in that case. If you want to make all requests within the same session then you will have to make use of the Cookies property of the response and the CookieContainer property of the subsequent request. I've never done that myself so I can't tell you exactly how but I know that there are examples on the web.
 
Back
Top