2012-03-08 33 views
1

我試圖在發佈請求中保存cookie。這裏是我的代碼:使用HttpWebRequest無法在wp7中獲取cookie

 CookieContainer myCookieContainer = new CookieContainer(); 
     HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
     myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; 
     myHttpWebRequest.UserAgent = userAgent; 
     myHttpWebRequest.CookieContainer = myCookieContainer; 
     myHttpWebRequest.Method = "POST"; 

     byte[] postdata = encoding.GetBytes(submitString); 

     myHttpWebRequest.BeginGetRequestStream(async1 => 
     { 
      using (Stream stream = myHttpWebRequest.EndGetRequestStream(async1)) 
       stream.Write(postdata, 0, postdata.Length); 
      myHttpWebRequest.BeginGetResponse(async2 => 
      { 
       HttpWebResponse rep = (HttpWebResponse)myHttpWebRequest.EndGetResponse(async2); 
       CookieCollection cookies = rep.Cookies; 
       using (Stream stream = rep.GetResponseStream()) 
       using (StreamReader sr = new StreamReader(stream)) 
       { 
        String content = sr.ReadToEnd(); 
        if (pageDownloadedEventHandler != null) 
         pageDownloadedEventHandler(content); 
       } 
      }, null); 
     }, null); 

Alaways的CookieContainer爲空。 如何獲取餅乾?

+0

您發送的請求沒有cookie,您確定服務器實際上是否設置了任何cookie來回傳? – 2012-03-08 17:53:47

+0

@JoachimIsaksson是的,我看到wireshark中的cookies – 2012-03-09 04:38:04

回答

1

如果服務器將您應該在rep.Cookies以及myCookieContainer中看到的任何Cookie發回給您,您的代碼似乎是完美的。

如果您想確保使用Fiddler或Wireshark來分析HTTP網絡流量並查找cookie,但如果我是對的,您將無法找到它們。在這種情況下,我的想法是分析網絡流量與您的瀏覽器做同樣的請求,也許php/asp.net /其他應用程序決定不會因爲某些缺少的請求標頭而設置cookie。

+0

感謝您的建議。我使用wireshark並找出服務器確實返回了cookie。我發現網站的過程必須經過兩次確認,而我所做的是第二次傳遞一個空的pageDownloadedEventHandler。在我將其更改爲真正的處理程序後,出現了Cookie。是否因爲異步代碼不會同步cookieContainer中的cookie? – 2012-03-09 04:39:04

+0

cookie容器在異步請求的情況下也同步。可能因爲您沒有指定下載的事件處理程序,該庫假定您不需要任何響應數據,因此它沒有收到任何響應數據。 – 2012-03-09 08:20:09