Showing posts with label winhttpopen. Show all posts
Showing posts with label winhttpopen. Show all posts

Tuesday, April 7, 2020

c++ winhttp example

#include <windows.h>
#include <winhttp.h>
#include <stdio.h>
#pragma comment(lib, "winhttp.lib")

int main()
{
    LPCWSTR httpUserAgent = L"neonprimetime Simulation/1.0";
    LPCWSTR httpUserAgentProxy = L"neonprimetime Proxy Simulation/1.0";
    //INTERNET_PORT httpPort = INTERNET_DEFAULT_HTTPS_PORT;
    INTERNET_PORT httpPort = INTERNET_DEFAULT_HTTP_PORT;
    //DWORD isHttpsEnabled = WINHTTP_FLAG_SECURE;
    DWORD isHttpsEnabled = 0;
    LPCWSTR httpHost = L"149.154.165.120";
    //LPCWSTR httpHost = L"www.microsoft.com";
    LPCWSTR httpFullUrl = L"http://149.154.165.120/";
    //LPCWSTR httpFullUrl = L"https://www.microsoft.com/";
    LPCWSTR httpMethod = L"GET";
    LPCWSTR httpPath = L"/";
    DWORD lenAvailableHtmlToDownload = 0;
    DWORD lenHtmlActuallyDownloaded = 0;
    LPSTR strDownloadedHtmlBuffer;
    BOOL isRequestSuccessful = FALSE;
    BOOL isProxyFound = FALSE;
    BOOL isProxySet = FALSE;
    HINTERNET  httpSession = NULL;
    HINTERNET  httpConnection = NULL;
    HINTERNET  httpRequest = NULL;

    // open user agent session
    httpSession = WinHttpOpen(httpUserAgent, WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
    if (httpSession)
    {
        printf("session opened\n");
        if (!WinHttpSetTimeouts(httpSession, 1000, 1000, 1000, 1000))
            printf("Error %u in WinHttpSetTimeouts.\n", GetLastError());

        printf("connection timeouts set\n");

        // open connection to host
        httpConnection = WinHttpConnect(httpSession, httpHost, httpPort, 0);
        if (httpConnection)
        {
            printf("connection opened\n");
            // open request to path
            httpRequest = WinHttpOpenRequest(httpConnection, httpMethod, httpPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, isHttpsEnabled);
            if (httpRequest)
            {
                printf("request opened\n");
                // send request to host
                isRequestSuccessful = WinHttpSendRequest(httpRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
                if (isRequestSuccessful)
                {
                    printf("requesst sent\n");
                    // receive response from host
                    isRequestSuccessful = WinHttpReceiveResponse(httpRequest, NULL);
                    if (isRequestSuccessful)
                    {
                        printf("response received\n");
                        do
                        {
                            // check if there is still more html available to download
                            lenAvailableHtmlToDownload = 0;
                            if (WinHttpQueryDataAvailable(httpRequest, &lenAvailableHtmlToDownload))
                            {
                                strDownloadedHtmlBuffer = new char[lenAvailableHtmlToDownload + 1];
                                if (strDownloadedHtmlBuffer)
                                {
                                    // clear out (with 0s) the previously downloaded html
                                    ZeroMemory(strDownloadedHtmlBuffer, lenAvailableHtmlToDownload + 1);
                                    // download html to the buffer
                                    if (WinHttpReadData(httpRequest, (LPVOID)strDownloadedHtmlBuffer, lenAvailableHtmlToDownload, &lenHtmlActuallyDownloaded))
                                    {
                                        printf("%4i bytes downloaded", lenHtmlActuallyDownloaded);
                                        if (lenHtmlActuallyDownloaded > 0)
                                        {
                                            if (lenHtmlActuallyDownloaded <= 10)
                                            {
                                                printf(",'%s'\n", strDownloadedHtmlBuffer);
                                            }
                                            else
                                            {
                                                const int lenSnippet = 25;
                                                char strFront[lenSnippet + 1];
                                                char strBack[lenSnippet + 1];
                                                strncpy_s(strFront, strDownloadedHtmlBuffer, lenSnippet);
                                                for (int i = 0; i < lenSnippet; i++)
                                                    if (strFront[i] == '\r' || strFront[i] == '\n')
                                                        strFront[i] = ' ';
                                                strFront[lenSnippet] = 0;
                                                strncpy_s(strBack, strDownloadedHtmlBuffer + (strlen(strDownloadedHtmlBuffer) - lenSnippet), lenSnippet);
                                                for (int i = 0; i < lenSnippet; i++)
                                                    if (strBack[i] == '\r' || strBack[i] == '\n')
                                                        strBack[i] = ' ';
                                                strBack[lenSnippet] = 0;
                                                printf(",'%s ... %s'\n", strFront, strBack);
                                                //printf(",'%s'\n", strDownloadedHtmlBuffer);
                                            }
                                        }
                                        else
                                            printf(",nothing actually downloaded");
                                    }
                                    else
                                    {
                                        printf("Error %u in WinHttpReadData.\n", GetLastError());
                                        lenAvailableHtmlToDownload = 0;
                                    }
                                    delete[] strDownloadedHtmlBuffer;
                                }
                                else
                                {
                                    printf("Out of memory\n");
                                    lenAvailableHtmlToDownload = 0;
                                }
                            }
                            else
                            {
                                printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError());
                                lenAvailableHtmlToDownload = 0;
                            }

                        } while (lenAvailableHtmlToDownload > 0);
                    }
                    else
                        wprintf(L"Http Received failed '%s', '%s', '%d', '%s', '%s', '%d'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath, GetLastError());
                }
                else {
                    wprintf(L"Http Send failed '%s', '%s', '%d', '%s', '%s', '%u'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath, GetLastError());
                    if (httpRequest) WinHttpCloseHandle(httpRequest);
                    if (httpConnection) WinHttpCloseHandle(httpConnection);
                    if (httpSession) WinHttpCloseHandle(httpSession);
                    // send failed, try with a proxy
                    WINHTTP_AUTOPROXY_OPTIONS  AutoProxyOptions;
                    WINHTTP_PROXY_INFO         ProxyInfo;
                    DWORD                      cbProxyInfoSize = sizeof(ProxyInfo);

                    ZeroMemory(&AutoProxyOptions, sizeof(AutoProxyOptions));
                    ZeroMemory(&ProxyInfo, sizeof(ProxyInfo));
                    httpSession = WinHttpOpen(httpUserAgentProxy, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);
                    if (httpSession)
                    {
                        printf("proxy re-opened session\n");
                        httpConnection = WinHttpConnect(httpSession, httpHost, httpPort, 0);
                        if (httpConnection)
                        {
                            printf("proxy re-opened connection\n");
                            httpRequest = WinHttpOpenRequest(httpConnection, httpMethod, httpPath, NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, isHttpsEnabled);
                            if (httpRequest)
                            {
                                printf("proxy re-opened request\n");
                                // discover the proxy auto config url
                                AutoProxyOptions.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
                                //AutoProxyOptions.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
                                AutoProxyOptions.lpszAutoConfigUrl = L"http://pac.somebody.com/proxy.pac";
                                AutoProxyOptions.fAutoLogonIfChallenged = TRUE;
                                isProxyFound = WinHttpGetProxyForUrl(httpSession, httpFullUrl, &AutoProxyOptions, &ProxyInfo);
                                if (isProxyFound)
                                {
                                    printf("proxy config url\n");
                                    isProxySet = WinHttpSetOption(httpRequest, WINHTTP_OPTION_PROXY, &ProxyInfo, cbProxyInfoSize);
                                    if (isProxySet)
                                    {
                                        printf("proxy set config url\n");
                                        isRequestSuccessful = WinHttpSendRequest(httpRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0);
                                        if (isRequestSuccessful)
                                        {
                                            printf("proxy sent request\n");
                                            // receive response from host
                                            isRequestSuccessful = WinHttpReceiveResponse(httpRequest, NULL);
                                            if (isRequestSuccessful)
                                            {
                                                printf("response received via proxy\n");
                                                do
                                                {
                                                    // check if there is still more html available to download
                                                    lenAvailableHtmlToDownload = 0;
                                                    if (WinHttpQueryDataAvailable(httpRequest, &lenAvailableHtmlToDownload))
                                                    {
                                                        strDownloadedHtmlBuffer = new char[lenAvailableHtmlToDownload + 1];
                                                        if (strDownloadedHtmlBuffer)
                                                        {
                                                            // clear out (with 0s) the previously downloaded html
                                                            ZeroMemory(strDownloadedHtmlBuffer, lenAvailableHtmlToDownload + 1);
                                                            // download html to the buffer
                                                            if (WinHttpReadData(httpRequest, (LPVOID)strDownloadedHtmlBuffer, lenAvailableHtmlToDownload, &lenHtmlActuallyDownloaded))
                                                            {
                                                                printf("%4i bytes downloaded", lenHtmlActuallyDownloaded);
                                                                if (lenHtmlActuallyDownloaded > 0)
                                                                {
                                                                    if (lenHtmlActuallyDownloaded <= 10)
                                                                    {
                                                                        printf(",'%s'\n", strDownloadedHtmlBuffer);
                                                                    }
                                                                    else
                                                                    {
                                                                        const int lenSnippet = 25;
                                                                        char strFront[lenSnippet + 1];
                                                                        char strBack[lenSnippet + 1];
                                                                        strncpy_s(strFront, strDownloadedHtmlBuffer, lenSnippet);
                                                                        for (int i = 0; i < lenSnippet; i++)
                                                                            if (strFront[i] == '\r' || strFront[i] == '\n')
                                                                                strFront[i] = ' ';
                                                                        strFront[lenSnippet] = 0;
                                                                        strncpy_s(strBack, strDownloadedHtmlBuffer + (strlen(strDownloadedHtmlBuffer) - lenSnippet), lenSnippet);
                                                                        for (int i = 0; i < lenSnippet; i++)
                                                                            if (strBack[i] == '\r' || strBack[i] == '\n')
                                                                                strBack[i] = ' ';
                                                                        strBack[lenSnippet] = 0;
                                                                        printf(",'%s ... %s'\n", strFront, strBack);
                                                                        //printf(",'%s'\n", strDownloadedHtmlBuffer);
                                                                    }
                                                                }
                                                                else
                                                                    printf(",nothing actually downloaded");
                                                            }
                                                            else
                                                            {
                                                                printf("Error %u in WinHttpReadData.\n", GetLastError());
                                                                lenAvailableHtmlToDownload = 0;
                                                            }
                                                            delete[] strDownloadedHtmlBuffer;
                                                        }
                                                        else
                                                        {
                                                            printf("Out of memory\n");
                                                            lenAvailableHtmlToDownload = 0;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        printf("Error %u in WinHttpQueryDataAvailable.\n", GetLastError());
                                                        lenAvailableHtmlToDownload = 0;
                                                    }

                                                } while (lenAvailableHtmlToDownload > 0);
                                            }
                                            else
                                                wprintf(L"Http Proxy Received failed '%s', '%s', '%d', '%s', '%s', '%d'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath, GetLastError());
                                        }
                                        else
                                            wprintf(L"Http Proxy Send failed '%s', '%s', '%d', '%s', '%s', '%u'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath, GetLastError());
                                    }
                                    else
                                        wprintf(L"Http Proxy Set failed '%s', '%s', '%d', '%s', '%s'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath);
                                }
                                else
                                    wprintf(L"Http Proxy Found failed '%s', '%s', '%d', '%s', '%s'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath);
                            }
                            else
                                wprintf(L"Http Proxy Request open failed '%s', '%s', , '%d''%s', '%s'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath);
                            if (httpConnection) WinHttpCloseHandle(httpConnection);
                        }
                        else
                            wprintf(L"Http Proxy Connection open failed '%s', '%s', '%d'\n", httpUserAgent, httpHost, httpPort);
                        if (httpSession) WinHttpCloseHandle(httpSession);
                    }
                    else
                        wprintf(L"Http Proxy Session open failed %s\n", httpUserAgent);\
                }
                if (httpRequest) WinHttpCloseHandle(httpRequest);
            }
            else
                wprintf(L"Http Request open failed '%s', '%s', , '%d''%s', '%s'\n", httpUserAgent, httpHost, httpPort, httpMethod, httpPath);
            if (httpConnection) WinHttpCloseHandle(httpConnection);
        }
        else
            wprintf(L"Http Connection open failed '%s', '%s', '%d'\n", httpUserAgent, httpHost, httpPort);
        if (httpSession) WinHttpCloseHandle(httpSession);
    }
    else
        wprintf(L"Http Session open failed %s\n", httpUserAgent);
}