What is the principle of getting cookies for future use? Now I use webbrowser for this and insert cookies from there into the request, but I would like to find a more rational way.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://kinopoisk.ru/s/type/all/find/"+"Хардкор"); request.Referer = "https://www.kinopoisk.ru/"; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586"; request.Accept = "text/html, application/xhtml+xml, image/jxr, */*"; request.Method = "POST"; request.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie); var responseToString = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.GetEncoding(1251)).ReadToEnd(); 

    1 answer 1

    The easiest thing is to use System.Net.CookieContainer

    Example:

     System.Net.CookieContainer cookies = new CookieContainer(); System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(uri); request.CookieContainer = cookies; ... // do something with request var response = request.GetResponse(); ... // do something with response 

    After the request has been completed, the cookies will be in cookies , they can be used in the next request, requestNext.CookieContainer = cookies

    An example and description can be found here.


    You can manually parse the Set-Cookie headers from the server. An example of how to do this is here.

    • Sample code that resulted here, does it write something to the variable cookies? - Andrey Fedorov
    • @ Andrei Fedorov, corrected a little, it was assumed that in ... // do something a request to the site will be executed request.GetResponse(); , after that cookies will be written to cookies from the Set-Cookie response header, and they can be further used - Evgenii Izhboldin
    • @Andrey Fedorov, the only thing was problems with the container in .NET 4, I didn’t want to take some cookies on one site, everything was fine on .NET 4.5, but I had to run it on XP, then I had to do it using the second method myself - Evgenii Izhboldin