检索和设置cookie

本文关键字:cookie 设置 检索 | 更新日期: 2023-09-27 18:18:16

我正在尝试连接到一个使用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包含了更多条目。

我的代码有什么问题?

检索和设置cookie

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

cookie = req.CookieContainer = new CookieContainer();

每次写完请求流后都实例化一个新的cookie容器。

由于cookie是一个全局变量,因此只初始化它一次,例如在声明它并在编写流之前设置它:

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