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

时间:2014-03-09 23:34:19

标签: c# cookies httpwebrequest

我用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();

1 个答案:

答案 0 :(得分:0)

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

myReq.CookieContainer = gaCookies