Wininet InternetGetCookie Receives Empty Cookie Data

I am currently working on receiving cookie data with Csharp. I use DLLImport to call InternetGetCookie in wininet.dll, but when I try it, the functions return ERROR_INSUFFICIENT_BUFFER (error code 122).

Can someone help me with this?

This is the Dll link code:

[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 how I call the function:

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

Thanks.

+6
source share
1 answer

The return value tells you that the buffer you provided to the function is not large enough to contain the data that it wants to return. You need to call InternetGetCookie twice: drive once at a rate of 0 to find out how big the buffer is; and the second time with a buffer of the right size.

Also, the P / Invoke signature is incorrect; StringBuilder must not be a ref parameter (and the EntryPoint parameter is EntryPoint because it does not specify the correct entry point name).

Declare the function as follows:

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

Then name it like this:

 // 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(); 
+9
source

Source: https://habr.com/ru/post/913319/


All Articles