检索并设置cookie

时间:2011-12-16 12:13:13

标签: c# .net cookies

我正在尝试连接到使用Cookie的网站。我的登录信息如下:

        private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseurl);

            req.Referer = referer;
            req.AllowAutoRedirect = true;
            req.KeepAlive = true; 
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] postbuf = Encoding.ASCII.GetBytes(login);
            req.ContentLength = postbuf.Length;
            Stream rs = req.GetRequestStream();
            rs.Write(postbuf, 0, postbuf.Length);
            rs.Close();

            cookie = req.CookieContainer = new CookieContainer();

            WebResponse resp = req.GetResponse();

            string s = "";
            foreach (Cookie c in cookie.GetCookies(req.RequestUri))
            {
                s += ("Cookie['" + c.Name + "']: " + c.Value);
            }
            textBox1.Text = s;

            resp.Close();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }

Cookie包含2个带值的键。然后我尝试按如下方式向网站发送帖子请求:

        private void button2_Click(object sender, EventArgs e)
    {
        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(search);

            req.Referer = referer;
            req.AllowAutoRedirect = true;
            req.KeepAlive = true;
            req.CookieContainer = cookie;
            StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream());

            if (reader != null)
            {
                string data = reader.ReadToEnd();
                reader.Close();

                textBox1.Text = data;
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex);
        }
    }

但是我收到一个无法验证的错误。当我使用firefox登录时,我发现cookie包含更多条目。

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

我认为你的错误在以下几行:

cookie = req.CookieContainer = new CookieContainer();

每次编写请求流后,您都要实例化一个新的cookie容器。

因为cookie是一个全局变量,所以只初始化它,例如声明它的位置,并在写入流之前设置它:

req.CookieContainer = cookie;
rs.Write(postbuf, 0, postbuf.Length);