El TecnoBaúl de Kiquenet

Kiquenet boring stories

Archive for 18 febrero 2010

Sending/receiving cookies with HttpWebRequest/HttpWebResponse

Posted by kiquenet en 18 febrero 2010

When using a HttpWebRequest or a HttpWebResponse, you might need to send or receive cookies. If you try to access directly the Cookie property of your HttpWebRequest, no cookie will be returned.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/MyApp/MyPage");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// response.Cookies is always empty

It’s a bit tricky, but to be able to access the cookies, you need to first assign the CookieContainer of your request.

A CookieContainer contains cookies for many requests. In fact, while the CookieCollection just store a list of Cookie, the CookieContainer store many CookieCollection, each for a specified URI. It allows storing cookies for different URI in a single place.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/MyApp/MyPage");
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.Cookies != null && response.Cookies.Count != 0)
{
    foreach(Cookie cookie in response.Cookies)
    {
      // Access to each cookie here
    }
}
else
{
    // No cookie
}

In some cases, you might need to perform several requests, GET or POST, toward several URLs, and pass each time the cookie information gathered from the previous requests. The easiest way to do that is to reuse your CookieContainer object. For instance:

CookieContainer cookieContainer = new CookieContainer();

HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("http://localhost/MyApp/MyPage1");
request1.CookieContainer = cookieContainer;
HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();

// Do something here

HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("http://localhost/MyApp/MyPage2");
request2.CookieContainer = cookieContainer;
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();

By doing this way, you share your cookies between the two requests. The cookies retrieve in response1 are store in your cookieContainer, and then sent within request2. Cookies retrieved in response2 are added or updated inside your cookieContainer, and so on.

menet.name/blog/christophe

Posted in ASP.NET | Etiquetado: , , | Leave a Comment »