Wininet InternetGetCookie gets empty cookie data
Asked Answered
T

1

10

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.

Teel answered 16/4, 2012 at 12:56 Comment(0)
C
16

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();
Columbary answered 16/4, 2012 at 14:21 Comment(1)
My god, what a terrible API :D But thanks, I needed that, too.Flybynight

© 2022 - 2024 — McMap. All rights reserved.