C# HttpWebRequest获取COOKIES

C# HttpWebRequest获取COOKIES

 

byte[] bytes = Encoding.Default.GetBytes(_post);
                CookieContainer myCookieContainer = new CookieContainer();
                try
                {
                    //新建一个CookieContainer
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(_loginurl);
                    //新建一个HttpWebRequest
                    myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    myHttpWebRequest.AllowAutoRedirect = false;
                    myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
                    myHttpWebRequest.Timeout = 60000;
                    myHttpWebRequest.KeepAlive = true;
                    myHttpWebRequest.ContentLength = bytes.Length;
                    myHttpWebRequest.Method = "POST";
                    myHttpWebRequest.CookieContainer = myCookieContainer;
                    //设置HttpWebRequest
                    Stream myRequestStream = myHttpWebRequest.GetRequestStream();
                    myRequestStream.Write(bytes, 0, bytes.Length);
                    myRequestStream.Close();
                    HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    foreach (Cookie ck in myHttpWebResponse.Cookies)
                    {
                        myCookieContainer.Add(ck);
                    }
                    myHttpWebResponse.Close();
                }
                catch
                {
                    MessageBox.show("获取COOKIES失败!");
                    return;
                }

 

posted @ 2016-12-02 07:39  shiningrise  阅读(1075)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css