2012-08-14 91 views
-1

我有一個要求從登錄中獲取cookie的要求,因爲我會將這個cookie應用於同一頁面。這裏是我的代碼我無法從C#HTTPWebRequest獲取cookie

 string boundary = "41184676334"; 
     string username = "username"; 
     string password = "password"; 


     string login_post_data = 
       "POSTDATA=-----------------------------" + boundary + 
       "\nContent-Disposition: form-data; name=\"login\"" + 
       "\n\n" + username + 
       "\n-----------------------------" + boundary + 
       "\nContent-Disposition: form-data; name=\"key\"" + 
       "\n\n" + password + 
       "\n-----------------------------" + boundary + 
       "\nContent-Disposition: form-data; name=\"clcode\"" + 
       "\n\n" + 
       "\n-----------------------------" + boundary + "--"; 

     var cookies = new CookieContainer(); 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://site.com/cgi-bin/login.pl?logout"); 
     request.CookieContainer = cookies; 



     request.Method = "POST"; 
     request.ContentType = "multipart/form-data; boundary=---------------------------" + boundary; 

     request.Host = "site.com"; 
     request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:14.0) Gecko/20100101 Firefox/14.0.1"; 
     request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
     request.Referer = "https://site.com/cgi-bin/login.pl?logout"; 
     //request.Headers.Add("POSTDATA", post_data); 

     using (var requestStream = request.GetRequestStream()) 
     { 
      requestStream.Write(StrToByteArray(login_post_data), 0, StrToByteArray(login_post_data).Length); 
     } 



     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 



     using (Stream stream = response.GetResponseStream()) 
     { 


      StreamReader reader = new StreamReader(stream); 

      string temp = reader.ReadToEnd(); 
      richTextBox1.Text = temp; 
     } 


     foreach (string c in response.Cookies) 
     { 
      listBox1.Items.Add(c); 
     } 

的事情是「https://site.com/cgi-bin/login.pl?logout」是在同一頁我登錄後,我需要傳遞Cookie

回答

0

它看起來像您嘗試登錄,並在同一時間與您的要求,發送到URL

https://site.com/cgi-bin/login.pl?logout 

取出?logout參數,然後再試一次註銷。如果它沒有改變任何東西,請更新您的問題。

請進一步解釋,你試圖達到什麼目標,所以我們可以討論代碼是否正確。

+0

網址https://site.com/cgi-bin/login.pl?logout是我放置用戶名和密碼後的登錄頁面,點擊提交按鈕時,地址欄上顯示的是同一網址,但網頁的佈局是不同的。我想要做的是獲取cookie。顯然我的代碼沒有完成這項工作。 – 2012-08-22 19:53:03

+0

登錄頁面後面的網頁假設在其document.cookie中有一個cookie值,但它沒有 – 2012-08-29 19:34:59