谢谢大家...我研究了您的答案,是的,它起作用了...我可以使用一些有效凭据登录Facebook...太好了!!!:) 下面是我的最终代码:-
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;
string getUrl = "https://www.facebook.com/login.php?login_attempt=1";
string postData = String.Format("email={0}&pass={1}", "", "");
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();
ViewBag.Message = sourceCode;
}
当然,除了 httpwebrequest 和 httpwebresponse 之外,代码中还有很多其他的东西......
1)您必须运行两次 httpwebrequest 才能首先获取 cookie 集合,然后使用相同的 cookiecollection 实际登录因为 facebook 在登录前设置了某些 cookie它需要在登录时获取...
2)(这是我之前的问题的答案,即如何检查 URL 是否正常工作)所以你要做的是获取字符串中的页面内容(在本例中为 sourceCode)n 然后只需搜索你认为的特定字符串可能出现在结果页面中......就像在这种情况下,如果我成功登录,我可能会被重定向到 FB 上用户的主页。并且该页面可能包含用户名或页面标题之类的内容是“Facebook”...... n 等等......这样我们如何检查带有或不带凭据的 URL 是否成功......
就是这样......这个简单的事情花了我差不多三天......!荒谬的!