使用cookies(httpWebRequest,c#)

时间:2012-07-23 18:18:25

标签: c# cookies httpwebrequest httpwebresponse

我在网站上阅读了关于httpWebRequest和Cookies的完整答案,但我的问题仍然没有解决。我有一个winform应用程序登录到一个网站(正确记录),但我不能使用它的cookie仍然登录到另一个页面,我尝试了许多解决方案,如使用PHPSESSID,在两个请求中使用单个CookieContainer但没有一个很有效。 这是我的代码:

           HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("(Login page)");

        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.KeepAlive = true;

        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes("username=uname&password=pass&submit=Button");

        webRequest.ContentLength = data.Length;
        CookieContainer CookieContainer = new CookieContainer();
        webRequest.CookieContainer = CookieContainer;


        Stream newStream = webRequest.GetRequestStream();
        newStream.Write(data, 0, data.Length);
        newStream.Close();
        HttpWebResponse webResponse;
        webResponse = (HttpWebResponse)webRequest.GetResponse();
        HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create("(My control panel page)");
        webRequest1.Method = "GET";
        webRequest1.KeepAlive = true;
        webRequest1.CookieContainer=new CookieContainer();
        foreach (Cookie cook in webResponse.Cookies)
        {
            webRequest1.CookieContainer.Add(cook);
        }
        webRequest.ContentType = "application/x-www-form-urlencoded";

        webResponse = (HttpWebResponse)webRequest1.GetResponse();



        string html;
        using (Stream strmresponse = webResponse.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(strmresponse, Encoding.UTF8))
            {
                html = reader.ReadToEnd();
            }
        }
        textBox1.Text = html;

1 个答案:

答案 0 :(得分:1)

不确定您是否仍在意,但请查看this question的答案,因为它显示了如何为多个请求重复使用Cookie。