1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
|
class http_download
{
private:
std::wstring url_;
std::wstring cache;
HINTERNET internet_connection;
HINTERNET session;
HINTERNET request;
std::wstring host;
std::wstring object;
DWORD read_bytes__;
DWORD file_size_;
bool index_file;
public:
http_download(){}
http_download(std::wstring _url_)
{
this->set_url(_url_);
}
void set_url(std::wstring _url_)
{
this->file_size_ = 0;
this->read_bytes__ = 0;
this->url_ = _url_;
std::wstring url_copy(this->url_);
if(url_copy.find(L"http://") != std::wstring::npos)
{
url_copy.erase(0, url_copy.find(L"http://") + std::wstring(L"http://").size());
}
this->index_file = (url_copy.find(L'/') == std::wstring::npos) || (url_copy.find(L'/') == (url_copy.size() - 1));
if(!index_file)
{
this->host = url_copy.substr(0, url_copy.find(L'/'));
this->object = url_copy.substr(url_copy.find(L'/')+1, url_copy.size());
std::wcout << host << object << std::endl;
}
else
{
this->host = url_copy;
this->object = L"/";
}
}
bool connect()
{
session = InternetOpenW(0, INTERNET_OPEN_TYPE_PRECONFIG , 0, 0, 0);
std::wcout << "InternetOpen " << GetLastError() << std::endl;
if(session)
{
this->internet_connection = InternetConnectW(session, host.c_str(), INTERNET_DEFAULT_HTTP_PORT, 0, 0, INTERNET_SERVICE_HTTP, 0 ,0);
std::wcout << "InternetConnect " << GetLastError() << std::endl;
if(!internet_connection) return false;
else
{
const wchar_t* val[] = {L"*/*\0", NULL};
request = HttpOpenRequestW(internet_connection, L"GET", this->object.c_str(), NULL, NULL, val , 0, 0);
std::wcout << "HttpOpenRequest " << GetLastError() << std::endl;
if(request)
{
HttpSendRequestW(request, NULL, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, NULL, 0);
std::wcout << "HttpSendRequest " << GetLastError() << std::endl;
DWORD buffer_size = sizeof(this->file_size_);
if(HttpQueryInfoW(request, 0 , &this->file_size_, &buffer_size, NULL))
this->file_size_ = 0;
std::wcout << "HttpQueryInfo " << GetLastError() << std::endl;
return true;
}
return false;
}
}
else return false;
}
bool download()
{
DWORD read_bytes_ = 0;
wchar_t buffer[64];
InternetReadFile(request, &buffer, 64, &read_bytes_);
if(!read_bytes_)
{
this->read_bytes__ = 0;
return false;
}
this->read_bytes__ += read_bytes_;
cache += buffer;
return true;
}
const DWORD read_bytes() const
{
return read_bytes__;
}
const DWORD download_size() const
{
return file_size_;
}
const wchar_t* get_cache() const
{
return cache.c_str();
}
};
|