C# – HttpWebRequest POST (Login to Facebook)

I’m glad you found your answer, I could login facebook using HttpWebRequest too, just like you said.. Here’s an acceptable workaround:

First request: Get the cookies.

 CookieCollection cookies = new CookieCollection();
 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com); 
 request.CookieContainer = new CookieContainer();
 request.CookieContainer.Add(cookies);
 //Get the response from the server and save the cookies from the first request..
 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
 cookies = response.Cookies;

Second request: POST the form data and recover the cookies from the first request..

 string getUrl = "https://www.facebook.com/login.php?login_attempt=1";
 string postData = String.Format("email={0}&pass={1}", "value1", "value2");
 HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
 getRequest.CookieContainer = new CookieContainer();
 getRequest.CookieContainer.Add(cookies); //recover cookies First request
 getRequest.Method = WebRequestMethods.Http.Post;
 getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
 getRequest.AllowWriteStreamBuffering = true;
 getRequest.ProtocolVersion = HttpVersion.Version11;
 getRequest.AllowAutoRedirect = true;
 getRequest.ContentType = "application/x-www-form-urlencoded";

 byte[] byteArray = Encoding.ASCII.GetBytes(postData);
 getRequest.ContentLength = byteArray.Length;   
 Stream newStream = getRequest.GetRequestStream(); //open connection
 newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
 newStream.Close();

 HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
 using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
 {
   string sourceCode = sr.ReadToEnd();               
 } 

This is one of lots ways that works with HttpWebRequest, also if you prefer using WebBrowser, it works acceptable using the following:

webBrowser1.Navigate("https://www.facebook.com/login.php?login_attempt=1", "",byteArray, "Content-Type: application/x-www-form-urlencoded");

What I just realized is that it doesn’t work with the InternetSetCookie maybe the reason is because Cookies returned from Facebook have the “HttpOnly” attribute (true), and it can’t be accessible by client-side script.

Leave a Comment