2015-12-02 174 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

,但仍然添加它,并且通常它不会更改任何内容 –