2013-03-27 45 views
0

我沒有cookie的經驗,我試圖使用cookie(我從httpwebrequestPOST方法)訪問一個網站。在POST方法中,我完成了認證部分,最後我得到了cookie。我不知道如何使用這個cookie訪問一個網站,它類似於這個HttpWebRequest POST Method使用來自httpwebrequest的cookie訪問網站windows phone

希望任何人都可以給我一些建議,指針或一些示例代碼。謝謝你的幫助。

這是我迄今爲止的代碼。

private void GetResponseCallback(IAsyncResult asynchronousResult) 
     { 
      HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
      // End the operation 
      HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); 

      Stream streamResponse = response.GetResponseStream(); 
      StreamReader streamRead = new StreamReader(streamResponse); 

      using (IsolatedStorageFile isf = 
       IsolatedStorageFile.GetUserStoreForApplication()) 
      { 
       using (IsolatedStorageFileStream isfs = isf.OpenFile("CookieExCookies", 
        FileMode.OpenOrCreate, FileAccess.Write)) 
       { 
        using (StreamWriter sw = new StreamWriter(isfs)) 
        { 
         foreach (Cookie cookieValue in response.Cookies) 
         { 
          sw.WriteLine(cookieValue.ToString()); 
         } 
         sw.Close(); 
        } 
       } 
      } 
      // Close the stream object 
      streamResponse.Close(); 
      streamRead.Close(); 
      response.Close(); 

      //allDone.Set(); 
     } 

cookie存儲在文本框

private void ReadFromIsolatedStorage() 
    { 
     using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) 
     { 
      using (IsolatedStorageFileStream isfs = 
       isf.OpenFile("CookieExCookies", FileMode.OpenOrCreate)) 
      { 
       using (StreamReader sr = new StreamReader(isfs)) 
       { 
        tbTesting.Text = sr.ReadToEnd(); 
        sr.Close(); 
       } 
      } 
     } 
    } 
+1

看。 – 2013-03-27 06:08:13

回答

0

您可以使用的CookieContainer類的獲取和設置的cookie。當你使用它時,它會爲你處理所有事情。您不必手動設置cookie。檢查下面的代碼。

首先創建一個CookieContainer類的實例。

CookieContainer cookieContainer = new CookieContainer(); 

然後使用它進行認證,然後將其分配給每個請求你在的CookieContainer類用於身份驗證的內HttpWebRequest的

//Login request to get the cookie 
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://mydomain.com/login.svc"); 
req.Method = "POST"; 
if (req.SupportsCookieContainer) 
    req.CookieContainer = cookieContainer; 
.. rest of your code.. 

//Any other request which needs a cookie 
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://mydomain.com/getuserdata.svc"); 
req.Method = "POST"; 
if (req.SupportsCookieContainer) 
    req.CookieContainer = cookieContainer; 
.. rest of your code.. 
+0

Thx @nkchandra。我已經完成了登錄身份驗證部分,並獲得了會話cookie,以及我如何使用此會話cookie訪問網頁? – likewer 2013-03-28 00:40:13

+0

如果您使用我遵循的相同流程,它會更好。否則,你可以使用'req.CookieContainer.SetCookie()'方法 – nkchandra 2013-03-28 04:59:46

+0

第二種post方法可以讓webbrowser在登錄後顯示頁面嗎? – likewer 2013-03-28 05:32:54

相關問題