2010-06-04 38 views
23

我正在創建一個應用程序,從網頁中檢索數據。該頁面受密碼保護,並且在用戶登錄時創建Cookie。如何使用Cookie與HttpWebRequest

爲了檢索應用程序首先必須登錄的數據:使用用戶名和密碼進行網絡請求並存儲cookie。然後,當cookie被存儲時,它必須被添加到所有請求的標題中。

這裏是發出請求並檢索內容的方法:

public void getAsyncDailyPDPContextActivationDeactivation() 
    { 
     HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(dailyPDPContextActivationDeactivation); 

     IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null); 

     asyncResult.AsyncWaitHandle.WaitOne(); 

     using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult)) 
     using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream())) 
     { 
      string responseText = responseStreamReader.ReadToEnd(); 
     } 

    } 

有誰知道如何才能添加一個cookie到頁眉修改此方法?

下面是一個瀏覽器的請求的報頭結構的打印屏幕:

alt text http://img404.imageshack.us/img404/4793/cookiea.jpg

我將還感謝如果有人建議一種方法來存儲從響應的cookie(應用使得當請求http:xxx.xxx.xxx/login?username = xxx & password = xxx該cookie已創建,並且必須存儲以備將來的請求使用)。

回答

32
CookieContainer cookieContainer = new CookieContainer(); 
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(...); 
httpWebRequest.CookieContainer = cookieContainer; 

然後你再用這種的CookieContainer在隨後的請求:

HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(...); 
httpWebRequest2.CookieContainer = cookieContainer; 
+1

我不明白這一點其實。爲什麼你會把剛剛創建的cookiecontainer(所以它是空的)放入你要發送的請求中?難道它不是更合乎邏輯的,你必須在稍後填寫cookieContainer與響應?這是有原因的嗎?編輯:這樣給出了很多答案,但我無法弄清楚爲什麼這樣做。 – deltu100 2012-11-20 12:37:05

+0

我的應用程序有使用它的不良行爲。使用httpWebRequest2.Headers.Set(「Cookie」,...可以正常工作 – Eduardo 2012-12-27 21:46:41

+0

如果我以前登錄過網頁,我的HD上存儲了一個cookie,因此我可以跳過以編程方式登錄。網頁請求會自動搜索並找到包含找到的Cookie的內容,或者您​​是否必須手動執行此操作?如果後者出現問題,該如何做? – 2013-04-01 17:28:27

相關問題