Login to website using VB.NET
The example below uses HttpWebRequest and HttpWebResponse classes to log in to Facebook.
Dim cookieJar As New Net.CookieContainer() Dim request As Net.HttpWebRequest Dim response As Net.HttpWebResponse Dim strURL As String Try 'Get Cookies strURL = "https://login.facebook.com/login.php" request = Net.HttpWebRequest.Create(strURL) request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3" request.Method = "GET" request.CookieContainer = cookieJar response = request.GetResponse() For Each tempCookie As Net.Cookie In response.Cookies cookieJar.Add(tempCookie) Next 'Send the post data now request = Net.HttpWebRequest.Create(strURL) request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3" request.Method = "POST" request.AllowAutoRedirect = True request.CookieContainer = cookieJar Dim writer As StreamWriter = New StreamWriter(request.GetRequestStream()) writer.Write("email=username&pass=password") writer.Close() response = request.GetResponse() 'Get the data from the page Dim stream As StreamReader = New StreamReader(response.GetResponseStream()) Dim data As String = stream.ReadToEnd() response.Close() If data.Contains("<title>Facebook") = True Then 'LOGGED IN SUCCESSFULLY End If Catch ex As Exception MsgBox(ex.Message) End Try
Now, here is some explanation:
Get Cookies
The following block of code gets all the cookies from Facebook and stores them in a collection. These cookies are returned upon visiting the webpage: https://login.facebook.com/login.php. Getting the cookies is very important, because they must be passed back to the webpage when you are going to login.
For Each tempCookie As Net.Cookie In response.Cookies cookieJar.Add(tempCookie) Next
Passing post data to the website
Next, I created a StreamWriter class and wrote the post data to it. You can pass any data to the website here in name=value&name=value format.
Dim writer As StreamWriter = New StreamWriter(request.GetRequestStream()) writer.Write("email=username&pass=password") writer.Close()
Finally…
The following code gets the source code of the webpage returned which is the homepage of your account (i.e home.php), and checks if you are logged in successfully or not.
Dim stream As StreamReader = New StreamReader(response.GetResponseStream()) Dim data As String = stream.ReadToEnd() response.Close() If data.Contains("<title>Facebook") = True Then 'LOGGED IN SUCCESSFULLY End If
I hope this simple example will help you save some time. If you find it useful then do let me know via your comments.
Happy Coding
