posted on Friday, April 09, 2004 2:17 AM by taylorza

HttpWebRequest and persistent cookies

Today a poster wanted to know how to associate a persistent cookie with its URL when performing a HttpWebRequest to the URL. Fortunately I recently wrote an automated login application in C++ and knew of the WININET function InternetGetCookie, which returns the contents of a cookie related to a URL. I could not find a corresponding .NET method so I put toghether the following piece of code. It lacks decent error handling, but gets the cookies and builds a CookieContainer that can then be assigned to the CookieContainer of a HttpWebRequest.

[DllImport("wininet.dll", SetLastError=true)]
public static extern bool InternetGetCookie(
  string url, string cookieName,
  StringBuilder cookieData,
ref int size);

private static CookieContainer GetUriCookieContainer(Uri uri)
{
  CookieContainer cookies =
null;
 
 
// Determine the size of the cookie
  int datasize = 256;
  StringBuilder cookieData =
new StringBuilder(datasize);

  if (!InternetGetCookie(uri.ToString(), null, cookieData,
   
ref datasize))
 
{
   
if (datasize < 0) 
     
return null;

    // Allocate stringbuilder large enough to hold the cookie
   
cookieData = new StringBuilder(datasize);
   
if ( !InternetGetCookie(uri.ToString(), null, cookieData,
     
ref datasize) )
     
return null;
 
}

  if (cookieData.Length > 0)
 
{
   
cookies =
new CookieContainer();
   
cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
 
}
 
return cookies;
}

Comments