Passing cookie with HttpWebRequest in winforms?

后端 未结 1 1000
滥情空心
滥情空心 2021-01-15 05:47

Please see the following code:

    objCookieContainer = new CookieContainer();

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://websi         


        
相关标签:
1条回答
  • 2021-01-15 06:30
        private void button1_Click(object sender, EventArgs e)
        {
            var objCookieContainer = new CookieContainer();
    
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://website.com/login.php?user=xxx&pass=xxx");
            request.Method = WebRequestMethods.Http.Get;
            request.Timeout = 15000;
            request.Proxy = null;
            request.CookieContainer = objCookieContainer;
    
            HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create("http://website.com/page.php?link=url");
            newRequest.Method = WebRequestMethods.Http.Post;
            newRequest.Timeout = 15000;
            newRequest.Proxy = null;
    
    
            HttpWebResponse response = null;
    
            response = (HttpWebResponse)request.GetResponse();
            //once you read response u need to add all cookie sent in header to the 'objCookieContainer' so that it can be forwarded on second response
            foreach (Cookie cookie in response.Cookies)
            {
                objCookieContainer.Add(cookie);
            }
            string readerRequest = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
    
    
            //since you have added the cookies, this must response fine now
            newRequest.CookieContainer = objCookieContainer;
            response = (HttpWebResponse)newRequest.GetResponse();
            string readerNewRequest = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }
    

    if you are .NET version below 4.0 u may encounter a CookieContainer Bug : Check This Link

    0 讨论(0)
提交回复
热议问题