how to use cookies with HttpWebRequest

Niko Gamulin picture Niko Gamulin · Jun 4, 2010 · Viewed 37.7k times · Source

I am creating an application for data retrieval from the web page. The page is password protected and when the user logs in the cookie is created.

In order to retrieve the data the application first has to log in: make web request with username and password and store the cookie. Then when the cookie is stored it has to be added into the headers of all requests.

Here is the method which makes requests and retrieves the content:

public void getAsyncDailyPDPContextActivationDeactivation()
{
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(dailyPDPContextActivationDeactivation);

    IAsyncResult asyncResult = httpWebRequest.BeginGetResponse(null, null);

    asyncResult.AsyncWaitHandle.WaitOne();

    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult))
    using (StreamReader responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream()))
    {
        string responseText = responseStreamReader.ReadToEnd();
    }
}

Does anyone know how to modify this method in order to add a cookie into the header?

I would be also thankful if anyone suggested a way to store cookie from the response (when the application makes a request http:xxx.xxx.xxx/login?username=xxx&password=xxx the cookie is created and has to be stored for future requests).

Answer

k_b picture k_b · Jun 4, 2010
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest.CookieContainer = cookieContainer;

Then you reuse this CookieContainer in subsequent requests:

HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(...);
httpWebRequest2.CookieContainer = cookieContainer;