Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wininet InternetGetCookie gets empty cookie data

I'm currently working on getting cookie data with Csharp. I'm using DLLImport to invoke InternetGetCookie in wininet.dll, but when i try it the functions returns an ERROR_INSUFFICIENT_BUFFER (error code 122).

Can any one help me with this ?

This is the code of the Dll reference:

[DllImport("wininet.dll", SetLastError = true, CharSet = CharSet.Auto, EntryPoint="InternetGetCookie")]
        public static extern bool InternetGetCookie(string lpszUrl, string lpszCookieName,
            ref StringBuilder lpszCookieData, ref int lpdwSize);

And this is the how i call the function:

InternetGetCookie("http://example.com", null, ref lpszCookieData, ref size)

Thanks.

like image 568
P.G Wisgerhof Avatar asked Apr 16 '12 12:04

P.G Wisgerhof


1 Answers

The return value is telling you that the buffer you supplied to the function isn't big enough to contain the data it wants to return. You need to call InternetGetCookie twice: once passing in a size of 0, to find out how big the buffer should be; and a second time, with a buffer of the right size.

Additionally, the P/Invoke signature is wrong; StringBuilder should not be a ref parameter (and the EntryPoint parameter is wrong since it doesn't specify the correct entry point name).

Declare the function like this:

[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetGetCookie(string lpszUrl, string lpszCookieName,
    StringBuilder lpszCookieData, ref int lpdwSize);

Then call it like so:

// find out how big a buffer is needed
int size = 0;
InternetGetCookie("http://example.com", null, null, ref size);

// create buffer of correct size
StringBuilder lpszCookieData = new StringBuilder(size);
InternetGetCookie("http://example.com", null, lpszCookieData, ref size);

// get cookie
string cookie = lpszCookieData.ToString();
like image 178
Bradley Grainger Avatar answered Sep 18 '22 14:09

Bradley Grainger