Skip to content

Instantly share code, notes, and snippets.

@wtrsltnk
Last active April 3, 2021 19:05
Show Gist options
  • Save wtrsltnk/d3278e0d65c55a299dc1ed74a7eb19ea to your computer and use it in GitHub Desktop.
Save wtrsltnk/d3278e0d65c55a299dc1ed74a7eb19ea to your computer and use it in GitHub Desktop.
How to do a https request in win32
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <wininet.h>
#include <stdio.h>
int main()
{
static HINTERNET hInternet;
hInternet = InternetOpenA("wininet-test", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
const char* from = "https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html";
int retval = 0;
DWORD httpcode = 0;
DWORD dwordlen = sizeof (DWORD);
DWORD zero = 0;
HINTERNET hUrl = InternetOpenUrlA(hInternet, from, NULL, 0,
INTERNET_FLAG_HYPERLINK |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP |
INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
INTERNET_FLAG_NO_CACHE_WRITE |
INTERNET_FLAG_NO_COOKIES |
INTERNET_FLAG_NO_UI |
INTERNET_FLAG_RESYNCHRONIZE |
INTERNET_FLAG_RELOAD |
INTERNET_FLAG_SECURE, 0);
if (!hUrl) {
printf("InternetOpenUrl failed. err=%d", (int) GetLastError());
} else if (!HttpQueryInfo(hUrl, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &httpcode, &dwordlen, &zero)) {
printf("HttpQueryInfo failed. err=%d", (int) GetLastError());
} else if (httpcode != 200) {
printf("HTTP request failed with response code %d", (int) httpcode);
} else {
std::stringstream ss;
while (1) {
DWORD br = 0;
BYTE buf[1024 * 64];
if (!InternetReadFile(hUrl, buf, sizeof (buf), &br)) {
printf("InternetReadFile failed. err=%d", (int) GetLastError());
break;
} else if (br == 0) {
retval = 1;
break; /* done! */
} else {
ss.write((char*)buf,br);
}
}
std::cout << ss.str()<<std::endl;
}
InternetCloseHandle(hUrl);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment