Skip to content

Instantly share code, notes, and snippets.

@dustingetz
Created August 31, 2010 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustingetz/559317 to your computer and use it in GitHub Desktop.
Save dustingetz/559317 to your computer and use it in GitHub Desktop.
void Win32DownloadUrl(const TString& url, std::vector<char>& out_responsePayload)
{
OutputDebugString(boost::str(boost::wformat(L"Win32DownloadUrl(inner)\r\n")).c_str());
HINTERNET hINet = InternetOpen(TEXT("InetURL/1.0"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); //INTERNET_OPEN_TYPE_DIRECT INTERNET_OPEN_TYPE_PRECONFIG
if (!hINet)
{
OutputDebugString(boost::str(boost::wformat(L"Win32DownloadUrl(inner): couldn't fetch URL\r\n")).c_str());
DWORD lastError = GetLastError();
OutputDebugString(boost::str(boost::wformat(L"...GetLastError=%1%\r\n")%lastError).c_str());
DWORD error;
std::vector<wchar_t> buffer(1000);
DWORD size = buffer.size();
BOOL retval = InternetGetLastResponseInfo(&error, &buffer[0], &size);
assert(retval == TRUE);
OutputDebugString(boost::str(boost::wformat(L"...InternetGetLastResponseInfo=%1%\r\n")%(&buffer[0])).c_str());
throw boost::str(boost::wformat(L"Couldn't fetch URL: %1%\r\n") % url);
}
LPCTSTR headers = NULL;
DWORD headersLen = 0;
//DWORD dwFlags = 0;
DWORD dwFlags = INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_NO_UI|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_COOKIES;
DWORD_PTR dwContext = 0;
HINTERNET hFile = InternetOpenUrl( hINet, url.c_str(), headers, headersLen, dwFlags, dwContext);
if (!hFile)
{
OutputDebugString(boost::str(boost::wformat(L"Win32DownloadUrl(inner): couldn't fetch URL\r\n")).c_str());
DWORD lastError = GetLastError();
OutputDebugString(boost::str(boost::wformat(L"...GetLastError=%1%\r\n")%lastError).c_str());
DWORD error;
std::vector<wchar_t> buffer(1000);
DWORD size = buffer.size();
BOOL retval = InternetGetLastResponseInfo(&error, &buffer[0], &size);
assert(retval == TRUE);
OutputDebugString(boost::str(boost::wformat(L"...InternetGetLastResponseInfo=%1%\r\n")%(&buffer[0])).c_str());
InternetCloseHandle( hINet );
OutputDebugString(boost::str(boost::wformat(L"Win32DownloadUrl(inner): couldn't fetch url\r\n")).c_str());
throw boost::str(boost::wformat(L"Couldn't fetch URL: %1%") % url);
}
std::size_t response_i = 0;
DWORD dwRead;
while ( InternetReadFile( hFile, &out_responsePayload[response_i],
out_responsePayload.size() - response_i, &dwRead ) )
{
if ( dwRead == 0 )
break; //um what if its not done
response_i += dwRead;
bool atCapacity = (0 == out_responsePayload.size() - response_i);
if (atCapacity)
out_responsePayload.resize(2 * out_responsePayload.size());
}
InternetCloseHandle( hFile );
InternetCloseHandle( hINet );
OutputDebugString(boost::str(boost::wformat(L"Win32DownloadUrl(inner): succeeded")).c_str());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment