C# – HttpWebRequest POST(login到Facebook)

我试图在我的程序中login到Facebook,并从那里parsing一些信息(如姓名,个人资料图片等)。

每次执行下面的代码,我都会redirect到Facebook的主页面。

string email = "email"; string pw = "pw"; string PostData = String.Format("email={0}&pass={1}", email, pw); CookieContainer cookieContainer = new CookieContainer(); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(""); req.CookieContainer = cookieContainer; req.Method = "POST"; req.ContentLength = PostData.Length; req.ContentType = "application/x-www-form-urlencoded"; req.AllowAutoRedirect = true; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; ASCIIEncoding encoding = new ASCIIEncoding(); byte[] loginDataBytes = encoding.GetBytes(PostData); req.ContentLength = loginDataBytes.Length; Stream stream = req.GetRequestStream(); stream.Write(loginDataBytes, 0, loginDataBytes.Length); HttpWebResponse webResp = (HttpWebResponse)req.GetResponse(); Stream datastream = webResp.GetResponseStream(); StreamReader reader = new StreamReader(datastream); webBrowser1.DocumentText = reader.ReadToEnd(); foreach (Cookie cookies in webResp.Cookies) { MessageBox.Show(cookies.Name + " " + cookies.Value); } 

我在这里做错了什么? 任何帮助将不胜感激,非常感谢! 🙂

编辑:我发现后不久我怎么做。

Facebook每次访问它时都会发送一个cookie来查看是否启用了cookie,我所做的是向Facebook的login页面发送请求以获取cookie,然后再发送POST数据。 它以这种方式工作,我成功login。

不pipe怎么说,还是要谢谢你! 🙂

我很高兴你find你的答案,我也可以使用HttpWebRequestloginFacebook,就像你说的。这是一个可以接受的解决方法:

第一个要求获取cookie。

  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; 

第二次请求 POST表单数据并从第一个请求中恢复Cookie

  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(); } 

这是使用HttpWebRequest的很多方法之一,如果您更喜欢使用WebBrowser,则可以使用以下方法:

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

我刚刚意识到的是,它不能与InternetSetCookie一起工作,原因可能是因为从Facebook返回的Cookie具有“HttpOnly”属性(true),并且不能通过客户端脚本访问。

有时使用networking浏览器更容易,而且您可以运行隐藏在后台的浏览器。 稍后,您可以获取内部html或者可能下载一个图像。 无论你需要做什么。 这里是一个使用Windows窗体的例子。

创build一个新的胜利forms的应用程序,添加一个button,并粘贴该代码内。 不要添加任何东西,它应该工作…

 private void button1_Click(object sender, EventArgs e) { string email = "Your email"; string password = "your password"; // create a new browser WebBrowser w = new WebBrowser(); w.Dock = DockStyle.Fill; this.Controls.Add(w); // you may add the controll to your windows forms if you want to see what is going on // latter you may not chose to add the browser or you can even set it to invisible... // navigate to facebook w.Navigate(@"http://www.facebook.com/"); // wait a little for (int i = 0; i < 100; i++) { System.Threading.Thread.Sleep(10); System.Windows.Forms.Application.DoEvents(); } HtmlElement temp=null; // while we find an element by id named email while (temp == null) { temp = w.Document.GetElementById("email"); System.Threading.Thread.Sleep(10); System.Windows.Forms.Application.DoEvents(); } // once we find it place the value temp.SetAttribute("value", email); temp = null; // wiat till element with id pass exists while (temp == null) { temp = w.Document.GetElementById("pass"); System.Threading.Thread.Sleep(10); System.Windows.Forms.Application.DoEvents(); } // once it exist set it value equal to passowrd temp.SetAttribute("value", password); // if you already found the last fields the button should also be there... var inputs = w.Document.GetElementsByTagName("input"); int counter = 0; bool enableClick = false; // iterate through all the inputs in the document foreach (HtmlElement btn in inputs) { try { var att = btn.GetAttribute("tabindex"); var name = btn.GetAttribute("id"); if (enableClick)// button to submit always has a differnt id. it should be after password textbox { btn.InvokeMember("click"); counter++; } if (name.ToUpper().Contains("PASS") || att=="4") { enableClick = true; // button should be next to the password input } // try a max of 5 times if (counter > 5) break; } catch { } } } 

它工作的很好,仍然有点问题,当我尝试连接多个帐户,发生exception(超时),我意识到,Facebook禁止连续查询的连接,所以我尝试登出每次我想改变用户,但我失败。 这里我的鳕鱼退出:

  public void Logout() { loginResult = PostRequest.HttpPost( "https://www.facebook.com/logout.php", "fb_dtsg=AQAsBT0t&ref=mb&h=Affnf_e5MVZXT6Gj", cookieContainer); } 

之后,我得到的答复是用户仍然是conected

 webbrowser1.navigate("www.facebook.com"); webbrowser1.GetElementByiId("email").value="your mail ID"; webbrowser1.GetElementByiId("pass").value="password"; HtmlElement form = webBrowser1.Document.GetElementById("FormID"); if (form != null) form.InvokeMember("submit"); 

您是否将loginparameter passing给Facebooklogin页面? 如果是的话,Facebook不允许以任何方式做到这一点…