2012-09-29 19 views
1

更新1: 後/獲得標題的截圖:http://imageshack.us/photo/my-images/826/getpost.pngHttpWebRequest的resp.Headers [ 「設置Cookie」]爲空

我在尋找一個web請求幫助。請求的目的是登錄到一個站點並檢索Set-Cookie頭。我很感激任何幫助!

我對Web請求很陌生,所以請和我一起裸露。我試圖登錄到一個網站,並使用下面的代碼檢索cookie值。然而,在Set-Cookie頭總是空:

static void Main(string[] args) 
{ 
    string formUrl = "https://account.guildwars2.com/login"; 
    string formParams = string.Format("email={0}&password={1}", "xxx", "xxx"); 
    string cookieHeader; 
    var req = (HttpWebRequest)WebRequest.Create(formUrl); 
    req.Referer = "https://account.guildwars2.com/login"; 
    req.ContentType = "application/x-www-form-urlencoded"; 
    req.Method = "POST"; 
    req.KeepAlive = true; 
    byte[] bytes = Encoding.ASCII.GetBytes(formParams); 
    req.ContentLength = bytes.Length; 
    using (Stream os = req.GetRequestStream()) 
    { 
     os.Write(bytes, 0, bytes.Length); 
    } 
    WebResponse resp = req.GetResponse(); 
    cookieHeader = resp.Headers["Set-Cookie"]; 
} 

我不知道這有什麼關係重定向,因爲在C#應用程序,響應URI是「https://開頭的帳戶。 guildwars2.com/login?redirect_uri=/download」

響應頭鍍鉻

  • 的Content-Length:0
  • 的Content-Type:text/html的
  • 日期:星期六,2012年9月29日15時07分30秒GMT
  • 地點:下載
  • 服務器:Microsoft-IIS/7.5
  • 的Set-Cookie:S = 60B845F0-4E22-4A4B-890B-F3B885CEF9AE;域= guildwars2.com;路徑= /;版本= 1
  • X供電-通過:ARR /從C#應用2.5

響應

  • 內容長度:7344
  • 的Content-Type:text/html的
  • Date:Sat,29 Sep 2012 15:42:44 GMT
  • 服務器:Microsoft-IIS/7.5
  • X-已啓動方式:ARR/2.5
+2

我認爲你需要在發送前設置httpWebRequest.CookieCollection新CookieCollection,可能misstyped不是使用VS大氣壓。 –

+0

我試過req.CookieContainer = new CookieContainer();但沒有添加 – Skalis

回答

5

默認情況下,HttpWebRequest自動跟隨HTTP重定向響應,它阻止你捕捉Set-Cookie原始響應中的標題。要禁用此行爲,設置AllowAutoRedirectfalse發送請求之前:

req.AllowAutoRedirect = false; 
0

您可以嘗試使用這種方式獲取的cookie:

CookieContainer cookies = new CookieContainer(); 

WebResponse resp = req.GetResponse(); 

CookieCollection cookieCollection = cookies.GetCookies(request.RequestUri); 
+0

謝謝,但空的cookie收集。我開始認爲這與重定向有關。當我在谷歌調試時,它首先POST狀態303(重定向)登錄站點,然後獲取狀態200(確定)的下載網站。 – Skalis