Cookies

A cookie is a name/value string pair that an HTTP server sends to a client in a response header.

A web browser client typically remembers cookies, and replays them to the server in each subsequent request until their expiry.

A cookie allows a server to know whether it's talking to the same client.

By default, HttpWebRequest ignores any cookies received from the server.

To accept cookies, create a CookieContainer object and assign it to the WebRequest.

The cookies received in a response can then be enumerated.


using System;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
class ThreadTest
{
    static void Main()
    {
        var cc = new CookieContainer();

        var request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
        request.Proxy = null;
        request.CookieContainer = cc;
        using (var response = (HttpWebResponse)request.GetResponse())
        {
            foreach (Cookie c in response.Cookies)
            {
                Console.WriteLine(" Name: " + c.Name); 
                Console.WriteLine(" Value:  " + c.Value); 
                Console.WriteLine(" Path:  " + c.Path); 
                Console.WriteLine(" Domain: " + c.Domain);
            }
        }
    }
}

The output:


Name: PREF
 Value:  ID=cb381517b8a3f042:FF=0:TM=1292697686:LM=1292697686:S=2ChHqoVy2ucH4Mcv
 Path:  /
 Domain: .google.ca
 Name: NID
 Value:  42=GAwfQ-bE0QZ_7oesm0ZW-jBXs-D4Y17W9jLhp3BUkGraIdKis5o5mmJxwjL0orccq8XZOTHi2ZMO6nxgI7dWyDXv4p-e5ZQ1hj8kJpQTD95xZodUSU5jsvhr0_ssbKkm
 Path:  /
 Domain: .google.ca
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.