2012-07-23 62 views
0

我在网站上阅读了有关httpWebRequest和Cookies的完整答案,但我的问题仍未解决。我有一个登录到网站(记录正确)的winform应用程序,但我无法使用它的cookie来登录另一个网页,我尝试了很多解决方案,例如使用PHPSESSID,在两个请求中都使用一个CookieContainer,但没有一个是有效的。 这里是我的代码:使用Cookie(httpWebRequest,C#)

  HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("(Login page)"); 

     webRequest.Method = "POST"; 
     webRequest.ContentType = "application/x-www-form-urlencoded"; 
     webRequest.KeepAlive = true; 

     ASCIIEncoding encoding = new ASCIIEncoding(); 
     byte[] data = encoding.GetBytes("username=uname&password=pass&submit=Button"); 

     webRequest.ContentLength = data.Length; 
     CookieContainer CookieContainer = new CookieContainer(); 
     webRequest.CookieContainer = CookieContainer; 


     Stream newStream = webRequest.GetRequestStream(); 
     newStream.Write(data, 0, data.Length); 
     newStream.Close(); 
     HttpWebResponse webResponse; 
     webResponse = (HttpWebResponse)webRequest.GetResponse(); 
     HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create("(My control panel page)"); 
     webRequest1.Method = "GET"; 
     webRequest1.KeepAlive = true; 
     webRequest1.CookieContainer=new CookieContainer(); 
     foreach (Cookie cook in webResponse.Cookies) 
     { 
      webRequest1.CookieContainer.Add(cook); 
     } 
     webRequest.ContentType = "application/x-www-form-urlencoded"; 

     webResponse = (HttpWebResponse)webRequest1.GetResponse(); 



     string html; 
     using (Stream strmresponse = webResponse.GetResponseStream()) 
     { 
      using (StreamReader reader = new StreamReader(strmresponse, Encoding.UTF8)) 
      { 
       html = reader.ReadToEnd(); 
      } 
     } 
     textBox1.Text = html; 
+0

ContentType未设置为第二个请求。也许这不知何故影响服务器?你在webRequest.ContentType =“application/x-www-form-urlencoded”中看到错字吗?顺便说一句,我不认为这种内容类型适用于GET请求。 – 2012-07-23 18:46:45

+0

通常您只需使用相同的cookie容器,而不是从一个容器复制到另一个容器:webRequest1.CookieContainer = CookieContainer;如果这不起作用,请捕获网络流量并与浏览器进行比较。 – bmm6o 2012-07-24 16:37:46

+0

@ bmm6o如何捕捉网络流量? – John 2012-07-24 17:36:32

回答

1

不知道如果你还在乎,但检查答案this question出来,因为它显示了如何重新使用Cookie的多个请求。

相关问题