//GetCookie.cpp
//需要wininet.lib
#include <windows.h>
#include <Wininet.h>
#include <iostream>
#include <string>
using namespace std;
void main()
{
char szURL[256]; // buffer to hold the URL
LPSTR lpszData = NULL; // buffer to hold the cookie data
DWORD dwSize=0; // variable to get the buffer size needed
// Insert code to retrieve the URL.
strcpy(szURL, "http://www.csdn.net");
lpszData = new char[0]; //这里先new了下,后面解释
retry:
// The first call to InternetGetCookie will get the required
// buffer size needed to download the cookie data.
if (!InternetGetCookie(szURL, NULL, lpszData, &dwSize))
{
// Check for an insufficient buffer error.
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
delete[] lpszData; //delete刚刚先new的那个
// Allocate the necessary buffer.
lpszData = new char[dwSize];
// Try the call again.
goto retry;
}
else
{
// Insert error handling code.
cout<<"Have some error.../n";
}
}
else
{
// Insert code to display the cookie data.
cout<<lpszData<<endl;
// Release the memory allocated for the buffer.
delete []lpszData;
// Set Cookies
InternetSetCookie("http://www.xxxxx.com", NULL, "TestData = Test; expires = Sat, 01-Jan-2005
00:00:00 GMT");
}
}
PS:
MSDN明明说InternetGetCookie(szURL, NULL, lpszData, &dwSize)中的lpszData可以为NULL,如果lpszData为NULL,dwSize将返回足够存储COOKIE的大小。但是,我设置lpszData = NULL,dwSize = 0调用函数时,InternetGetCookie(szURL, NULL, lpszData, &dwSize)调用直接成功。。然后就明显了,lpszData是空指针,以后对它的操作都是非法的。
所以,在这里先new了一下,就成了这个程序