2011-12-08 25 views
18

我试图登录到Facebook在我的程序,并从那里解析某些信息(如姓名,个人档案相片等)。C# - HttpWebRequest的POST(登录Facebook的)

我重新导向回到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的登录页面获取Cookie,然后用POST数据发送另一个。它以这种方式工作,我成功登录。

无论如何,谢谢! :)

+0

您是否阅读过Facebook API http://developers.facebook.com/blog/post/395/或http://facebooksdk.codeplex.com/ – Lloyd

+2

这是违反Facebook服务条款。 – bkaid

+0

由于这种原因,我经常不得不使用webrwser控件而不是HttpWebRequest。这个问题让我难以接受新的东西......再加上即使它是facebook的服务条款,它也可以用于道德上的东西...... –

回答

5

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

创建一个新的胜利窗体应用程序,添加一个按钮并粘贴里面的代码。不添加任何东西它应该工作...

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 
     { 

     } 
    } 
} 
+1

Facebook有一个API,原因在于抓取HTML并不是一个体面的建议, 。 – Lloyd

+0

我表示,在我的回复中,解决方案并不是最好的解决方案。我的解决方案可行我相信会有更好的解决方案,但我不认为我应该得到-1的解决方案。 –

+0

我没有把它记下来! – Lloyd

-4

你特林登录参数传递给Facebook登录页面?如果是的话,Facebook的不允许这样做,以任何方式......

34

我很高兴你找到你的答案,我可以用HttpWebRequest太登录博客,就像你说的..这里是一个可以接受的解决办法:

第一个请求获取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; 

要求 POST表单数据,并从第一个请求恢复饼干..

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的作品之一,也是如果你喜欢

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

:使用web浏览器,它使用了以下工作接受我刚刚意识到的是它不适用于InternetSetCookie,可能原因是因为从Facebook返回的Cookies具有“HttpOnly”属性(true),并且它不能由客户端脚本访问。

+0

非常好!那正是我正在寻找的。漂亮,干净,完整的例子。太好了,非常感谢。 –

+0

不客气!但请记住,这是针对FB服务条款的,因为我们只是为了教育目的,只是明智地使用它!欢呼@ patryk.beza – WhySoSerious

+0

哇。很好 。 ..谢谢:) –

-1
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"); 
+1

请问您可以添加一条评论,指出为什么你认为你的代码是这个问题的解决方案? – Trinimon

+0

没有评论,这只是一种填补自动形成。 – djsony90