0

我没有使用 cookie 的经验,我尝试使用 cookie(我从httpwebrequest POST方法获得)来访问网站。在POST方法中,我完成了身份验证部分,最后得到了 cookie。我不知道如何使用这个 cookie 访问一个网站,它类似于这个HttpWebRequest POST Method

希望任何人都可以给我一些建议,指针或一些示例代码。谢谢你的帮助。

这是我到目前为止完成的代码。

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();
        }

TextBox 中的 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();
                }
            }
        }
    }
4

1 回答 1

0

您可以使用 CookieContainer 类来获取和设置 cookie。当你使用它时,它会为你处理一切。您不必显式手动设置 cookie。检查下面的代码。

首先创建一个 CookieContainer 类的实例。

CookieContainer cookieContainer = new CookieContainer();

然后将其用于身份验证,然后将其分配给您用于身份验证的每个请求

//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..
于 2013-03-27T11:13:01.747 回答