如何在c#中使用HttpWebRequest发送cookie

本文关键字:HttpWebRequest 发送 cookie | 更新日期: 2023-09-27 17:49:15

我用6个文本框制作了一个短程序,我用cookie手动填充。现在我想让我的程序对特定的url进行操作,就好像它已经登录了。

我怎样才能得到那个?我尝试了这个,我得到http响应,我没有登录。

            string url = "myurl string";
            Uri target = new Uri(url);
            CookieContainer gaCookies = new CookieContainer();
            gaCookies.Add(new Cookie("__utma", textBox1.Text) { Domain= target.Host});
            gaCookies.Add(new Cookie("__utmb", textBox2.Text) { Domain = target.Host });
            gaCookies.Add(new Cookie("__utmc", textBox3.Text) { Domain = target.Host });
            gaCookies.Add(new Cookie("__utmz", textBox4.Text) { Domain = target.Host });
            gaCookies.Add(new Cookie("cookiename1", textBox5.Text) { Domain = target.Host });
            gaCookies.Add(new Cookie("cookiename2", textBox6.Text) { Domain = target.Host });
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            textBox7.Text = readStream.ReadToEnd();

如何在c#中使用HttpWebRequest发送cookie

需要设置HTTP请求的cookie容器。在创建HtppWebRequest后添加以下行。

myReq.CookieContainer = gaCookies