Proxy Downloader using WinHttp in cpp

107 Views Asked by At

I am new to c++ but have managed to write the following code using microsoft documentation / looking at online examples / borrowing some code.

I want this code to be process agnostic ie able to be run in the context of a user or as a service with or without a proxy.

Any help would be appreciated:

**edited to reflect working code (should have updated in another place)

std::string Downloader() {

BOOL  bResults = FALSE;

HINTERNET hSession = NULL,

    hConnect = NULL,

    hRequest = NULL;



// Use WinHttpOpen to obtain a session handle.

hSession = WinHttpOpen(NULL,

    WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,

    WINHTTP_NO_PROXY_NAME,

    WINHTTP_NO_PROXY_BYPASS, 0);



// Specify an HTTP server.

if (hSession)

    hConnect = WinHttpConnect(hSession, L"10.0.2.4:8000", INTERNET_DEFAULT_HTTP_PORT, 0);



// Create an HTTP Request handle.

if (hConnect)

    hRequest = WinHttpOpenRequest(hConnect, L"GET", L"hello.txt", NULL, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, 0);



// Send a Request.

if (hRequest)

    bResults = WinHttpSendRequest(hRequest, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0,  0, 0);


if (!bResults)

    printf("Error %d has occurred.\n", GetLastError());



WinHttpReceiveResponse(hRequest, 0);



DWORD responseLength, readDataLength = 0;

WinHttpQueryDataAvailable(hRequest, &responseLength);

std::string response(responseLength);

    WinHttpReadData(hRequest, &response[0], responseLength, &readDataLength);

printf("%s\n", response);



// Close any open handles.

if (hRequest) WinHttpCloseHandle(hRequest);

if (hConnect) WinHttpCloseHandle(hConnect);

if (hSession) WinHttpCloseHandle(hSession);

return response;

}
0

There are 0 best solutions below