在Windows Phone 7应用程序上无法使用HttpWebResponse获取httponly cookie

时间:2015-04-07 13:29:51

标签: c# windows-phone-7 cookies httpwebrequest

我正在使用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");
    }

我知道已经存在一些类似的问题,但我仍然无法使我的应用程序正常运行。

我希望我的问题很明确。

谢谢。

1 个答案:

答案 0 :(得分:0)

我终于找到了为什么它不起作用:我忘了声明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没有在容器中引用,但无论如何它们都在其中。

我希望它会有所帮助。