#include "stdafx.h" #include "HttpContent.h"
LPTSTR HttpContent::lpszDefaultAgent = TEXT("Arslanbar Client"); LPTSTR HttpContent::lpszDefaultServer = TEXT("zh.arslanbar.net"); INTERNET_PORT HttpContent::nDefaultPort = INTERNET_DEFAULT_HTTP_PORT;
HttpContent::HttpContent(void) { lpszAgent = lpszDefaultAgent; lpszServer =lpszDefaultServer; nPort = nDefaultPort;
lpData = NULL; dwSize = 0; }
HttpContent::~HttpContent(void) { Free(); }
/* This function can be called a few times to combine several resources into one block of memory */ void HttpContent::Download(bool bTerminate) { HINTERNET hInternet = InternetOpen(lpszAgent, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, NULL); HINTERNET hConnect = InternetConnect(hInternet, lpszServer, nPort, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, NULL); HINTERNET hRequest = HttpOpenRequest(hConnect, NULL, lpszPage, NULL, NULL, NULL, NULL, NULL); HttpSendRequest(hRequest, NULL, NULL, NULL, NULL);
DWORD dwAvailableSize; DWORD dwRead = 0; HANDLE hHeap = GetProcessHeap(); while (InternetQueryDataAvailable(hRequest, &dwAvailableSize, NULL, NULL), dwAvailableSize > 0) { if (lpData == NULL) lpData = (LPBYTE)HeapAlloc(hHeap, NULL, dwAvailableSize + bTerminate); else lpData = (LPBYTE)HeapReAlloc(hHeap, NULL, lpData, dwSize + dwAvailableSize + bTerminate); InternetReadFile(hRequest, lpData + dwSize, dwAvailableSize, &dwRead); dwSize += dwAvailableSize; } if (bTerminate) *(lpData + dwSize) = '\0'; // dwSize doesn't include the terminating NULL InternetCloseHandle(hRequest); InternetCloseHandle(hConnect); InternetCloseHandle(hInternet); }
/* Delete previously downloaded data */ bool HttpContent::Free(void) { if (lpData == NULL) return false;
HeapFree(GetProcessHeap(), NULL, lpData); lpData = NULL; dwSize = 0; return true; }
LPBYTE HttpContent::GetData(void) { return lpData; }
DWORD HttpContent::GetSize(void) { return dwSize; }
/* Save the buffer to a file */ void HttpContent::Save(LPTSTR lpszFileName) { FILE *fp; _tfopen_s(&fp, lpszFileName, TEXT("wb")); if (lpData != NULL) fwrite(lpData, dwSize, 1, fp); fclose(fp); }
|