使用HttpWebRequest(c#)登录facebookWeb表单
本文关键字:登录 facebookWeb 表单 HttpWebRequest 使用 | 更新日期: 2023-09-27 18:20:17
我的代码被卡住了。我只是想通过c#和httpweb请求访问facebook主页。
我正试图用做登录的事情
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://www.facebook.com/login.php?login_attempt=1");
string s = "email=XXXXX@mymail.com&pass=YYYYY";
CookieContainer cookies = new System.Net.CookieContainer();
request.Method = "POST";
request.AllowAutoRedirect = false;
request.MaximumAutomaticRedirections = 1;
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
request.KeepAlive = true;
request.Timeout = 10000;
request.CookieContainer = cookies;
request.ContentLength = s.Length;
byte[] bytes = Encoding.UTF8.GetBytes(s);
request.ContentLength = bytes.Length;
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close();
Console.WriteLine("'n Cookies count is :{0}", cookies.Count); //0, obviously
//get response and print it
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream response_stream = response.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(response_stream);
string response_string = sr.ReadToEnd();
Console.WriteLine("'n Cookies count is :{0}", cookies.Count);
好的。此时发生了两件事:
- 我存储了3个cookie(cookies.count)
- FB的HTML响应说我需要在浏览器中激活cookie
我的问题是:
- 上面的代码正确吗?如果是,为什么我会收到FB的cookie消息
- 如果我现在想导航到我的FB主页,我是否应该使用之前填写的cookie存储创建另一个请求主页URL
现已解决,谢谢。
问题是用于执行登录POST表单的字符串格式不正确。请确保包括与原始web表单中相同的params+值。
;)
如果你需要从Facebook上阅读一些内容,最好使用facebookapi。codeplex上有一个项目Facebookc#SDK,它可能很方便。