2015-12-02 177 views
0

以下代碼應該將用戶登錄,但不起作用。代碼使用9gag作爲示例,但總體思路應該可以在別處使用。用戶不能訪問他/她的個人資料。C#Httpwebrequest登錄系統

代碼有什麼問題?

using System; 
using System.IO; 
using System.Linq; 
using System.Net; 
using System.Text; 


    namespace ttp_B 
{ 
    internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      bool flag = false; 
      //string word_to_stop = "profile"; 
      string urltosite = "https://9gag.com/login"; // site that i'm trying to log in 
      string emailaddress = ""; 
      string password = ""; 
      var coo = new System.Net.CookieContainer(); 
      try 
      { 
       var request = System.Net.WebRequest.Create(urltosite) as System.Net.HttpWebRequest; 
       request.CookieContainer = coo; 
       request.Method = "POST"; 
       request.Proxy = new WebProxy("127.0.0.1", 8888); // fiddler 
                   //some extra headers 
       request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
       request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0"; 
       using (var stream = request.GetRequestStream()) 
       { 
        byte[] buffer = 
         Encoding.UTF8.GetBytes(
          string.Format(
           "csrftoken=&next=http%3A%2F%2F9gag.com%2F&location=1&username={0}&password={1}", emailaddress, password)); 
        //this text of request is correct I guess. Got it from fiddler btw. 
        stream.Write(buffer, 0, buffer.Length); 
        stream.Close(); 
       } 
       using (var response = request.GetResponse() as HttpWebResponse) 
       { 
        coo.Add(response.Cookies); // adding cookies, just to make this working properly 
        using (var sr = new System.IO.StreamReader(response.GetResponseStream())) 
        { 
         string http_code = sr.ReadToEnd(); // gettin' that new html document 
         //flag = (http_code.Contains(word_to_stop)); // looking for word that I'm sure exist after succesfull loggin' in 
                    //if(flag == true) 
                    //{ 
                    // console.writeline("Works"); 
                    //} 
        } 
       } 
      } 
      catch (WebException e) 
      { 
       Console.Write(e.ToString()); 
      } 
     } 
    } 
} 
+0

當我嘗試代碼,(與空電子郵件和密碼爲空),它打印「作品」。返回的html包含word_to_stop(profile),但是,顯然我沒有登錄。另一件事,當你添加cookie容器時,你不需要添加收到的cookie,他們已經在cookie容器中,你可以檢查自己 –

+0

好變量word_to_stop是錯誤的,然後,順便說一句。當我編譯代碼並檢查它在包裝中的數據包時,我無法看到與使用IE瀏覽器時相同的頁面(*使用WebView)。 @edit可能要使用WebBrowser類,似乎很容易 –

回答

0

就我所見,請求流在您進入響應之前未關閉。

簡化它應該是這樣的:

var stream = request.GetRequestStream(); 
tStream(buffer, 0, buffer.Length); 

//close the stream 
tStream.Close(); 

//go for the response 
request.GetResponse(); 
+0

那麼,我能夠讀取網站的響應,而無需關閉流 –

+0

,但仍然添加它,並且通常它不會更改任何內容 –