Automatic cookie handling C # .NET HttpWebRequest + HttpWebResponse

Is it possible to automatically handle cookies in .NET with HttpWebRequest / HttpWebResponse objects? I prefer to look for the equivalent of LWP :: UserAgent and its behavior (perl), only in the .NET environment.

Any suggestions or tips?

+54
c # cookies
Feb 21 '09 at 2:17
source share
1 answer

I think you are looking for the CookieContainer class. If I understand what you're trying to do right, you have separate objects for the request and response, and you want to automatically transfer the collection of response files to the next request cookie collection. Try using this code:

CookieContainer cookieJar = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com"); request.CookieContainer = cookieJar; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); int cookieCount = cookieJar.Count; 

Once you create a cookieJar and set it into a cookie Cookie, it will store all cookies that come from the response, so in the example above the number of cookie jugs will be 1 after it visits Google.com.The properties of the request and response cookie container will be higher contain a pointer to a cookieJar, so cookies are automatically processed and shared between objects.

+123
Feb 21 '09 at 3:44
source



All Articles