簡體   English   中英

在Windows Phone 7應用程序上無法使用HttpWebResponse獲取httponly cookie

[英]Cannot get an httponly cookie with HttpWebResponse on windows phone 7 app

我正在為項目開發使用C#的應用程序,並且在網站上進行POST請求后需要獲取Cookie。 我正在使用HttpWebResponse來獲取請求的結果。 我的問題是CookieCollection為空,我不知道為什么。 該cookie是否可能因為它是HTTPOnly cookie而沒有出現?

這是我的整個POST請求的代碼:

    private void RequestPOST(string uri)
    {
        Uri myUri = new Uri(uri);

        HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
        myRequest.Method = "POST";
        myRequest.ContentType = "application/x-www-form-urlencoded";
        Debug.WriteLine("RequestStream : BEGIN");
        myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);

    }

    private void GetRequestStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
        Stream postStream = myRequest.EndGetRequestStream(callbackResult);

        byte[] byteArray = Encoding.UTF8.GetBytes(this._postData);

        postStream.Write(byteArray, 0, byteArray.Length);
        postStream.Close();

        myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);

    }

    private void GetResponsetStreamCallback(IAsyncResult callbackResult)
    {
        HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;

        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);

        CookieCollection cookies = response.Cookies;

        using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
        {
            this._retourPost = httpWebStreamReader.ReadToEnd();

            Debug.WriteLine(cookies.Count);//My problem appears here, cookieCount throws a NullException
            foreach (Cookie cook in response.Cookies)
            {
                Debug.WriteLine(cook.Name + " : "+ cook.Value);
            }
        }
        Debug.WriteLine("END");
    }

我知道已經有一些類似的問題,但是我仍然無法使我的應用程序正常運行。

希望我的問題清楚。

謝謝。

我終於找到了為什么它不起作用:我忘了聲明HttpWebRequest的cookiecontainer。 因此,我使用一個本地字段來保存CookieContainer,並在每次對RequestPOST()的調用中重用它。

    private CookieContainer cookiecontainer = new CookieContainer();

    private void RequestPOST(string uri)
    {
         Uri myUri = new Uri(uri);

         HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
         myRequest.Method = "POST";
         myRequest.ContentType = "application/x-www-form-urlencoded";

         myRequest.CookieContainer = this.cookiecontainer;

         Debug.WriteLine("RequestStream : BEGIN");
         myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);

    }

實際上,我不必閱讀HTTPOnly cookie,我只需要擁有它。 CookieContainer仍然不顯示cookie,因為在容器中未引用HTTPOnly cookie,但它們仍然存在於其中。

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM