The example below uses HttpWebRequest and HttpWebResponse classes to log in to Facebook.
^ Finally, it 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.
I hope this code will help you to save some time. If you find it useful then do let me know via your comments.
Code:
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.
For Each tempCookie As Net.Cookie In response.Cookies
cookieJar.Add(tempCookie)
Next
The block of code above gets all the cookies and stores it in a collection, which are returned upon visiting the webpage: https://login.facebook.com/login.php. These cookies are important because they must be passed back to the webpage when you are going to login.
Dim writer As StreamWriter = New StreamWriter(request.GetRequestStream())
writer.Write("email=username&pass=password")
writer.Close()
The code above creates a StreamWriter class and writes the post data to it. You can pass any data here to the website in name=value&name=value format.
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 code will help you to save some time. If you find it useful then do let me know via your comments.