-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_request.cpp
More file actions
85 lines (73 loc) · 2.62 KB
/
http_request.cpp
File metadata and controls
85 lines (73 loc) · 2.62 KB
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
#include "http_request.hpp"
#include <cstring>
#include <regex>
void* HttpRequest::VxMoveMemory(void* dest, const void* src, SIZE_T len)
{
char* d = static_cast<char*>(dest);
const char* s = static_cast<const char*>(src);
if (d < s)
while (len--)
*d++ = *s++;
else
{
const char* lasts = s + (len - 1);
char* lastd = d + (len - 1);
while (len--)
*lastd-- = *lasts--;
}
return dest;
}
bool HttpRequest::ParseURL(const std::wstring& url, std::wstring& host, INTERNET_PORT& port, std::wstring& path)
{
std::wregex urlRegex(L"(http://|https://)?([^:/]+):?(\\d*)(/.*)?");
std::wsmatch matches;
if (std::regex_match(url, matches, urlRegex)) {
host = matches[2].str();
port = matches[3].length() > 0 ? std::stoi(matches[3].str()) : 80;
path = matches[4].length() > 0 ? matches[4].str() : L"/";
return true;
}
return false;
}
HINTERNET HttpRequest::OpenSession()
{
return WinHttpOpen(L"WinHTTP Example/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
}
HINTERNET HttpRequest::ConnectToServer(HINTERNET hSession, const std::wstring& szServerName, INTERNET_PORT nServerPort)
{
return WinHttpConnect(hSession, szServerName.c_str(), nServerPort, 0);
}
HINTERNET HttpRequest::OpenRequest(HINTERNET hConnect, const std::wstring& szPath)
{
return WinHttpOpenRequest(hConnect, L"GET", szPath.c_str(), NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);
}
bool HttpRequest::SendRequest(HINTERNET hRequest)
{
return WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) != 0;
}
bool HttpRequest::ReceiveResponse(HINTERNET hRequest)
{
return WinHttpReceiveResponse(hRequest, NULL) != 0;
}
void* HttpRequest::ReadResponse(HINTERNET hRequest, void* lpAddress, SIZE_T sDataSize)
{
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
DWORD_PTR hptr = reinterpret_cast<DWORD_PTR>(lpAddress);
do
{
dwSize = 0;
if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) break;
std::vector<unsigned char> pszOutBuffer(dwSize + 1, 0);
if (!WinHttpReadData(hRequest, pszOutBuffer.data(), dwSize, &dwDownloaded)) break;
VxMoveMemory(reinterpret_cast<void*>(hptr), pszOutBuffer.data(), dwSize);
hptr += dwSize;
} while (dwSize > 0);
return lpAddress;
}
void HttpRequest::CloseHandles(HINTERNET hRequest, HINTERNET hConnect, HINTERNET hSession)
{
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);
}