HTTP POST and GET Requests with WinInet and C++

InternetOpenA
InternetConnectA
HttpOpenRequestA
HttpSendRequestA
InternetCloseHandle

Method to make POST or GET requests:

void Request(int Method, LPCSTR Host, LPCSTR url, LPCSTR header, LPSTR data)
{
try{
	//Retrieve default http user agent
	char httpUseragent[512];
	DWORD szhttpUserAgent = sizeof(httpUseragent);
	ObtainUserAgentString( 0, httpUseragent, &szhttpUserAgent );
 
	char m[5];
 
	if(Method == GET)
		strcpy(m, "GET");
	else 
		strcpy(m, "POST");
 
	//http://msdn.microsoft.com/en-us/library/windows/desktop/aa385096%28v=vs.85%29.aspx
	HINTERNET internet = InternetOpenA(httpUseragent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if(internet != NULL)
	{
		//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384363%28v=vs.85%29.aspx
		HINTERNET connect = InternetConnectA(internet, Host, INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
		if(connect != NULL)
		{
			//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384233%28v=vs.85%29.aspx
			HINTERNET request = HttpOpenRequestA(connect, m, url, "HTTP/1.1", NULL, NULL, 
				INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_IGNORE_CERT_CN_INVALID |
					INTERNET_FLAG_IGNORE_CERT_DATE_INVALID |
					INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP  |
					INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS |
					INTERNET_FLAG_NO_AUTH |
					INTERNET_FLAG_NO_CACHE_WRITE |
					INTERNET_FLAG_NO_UI |
					INTERNET_FLAG_PRAGMA_NOCACHE |
					INTERNET_FLAG_RELOAD, NULL);
 
			if(request != NULL)
			{
				int datalen = 0;
				if(data != NULL) datalen = strlen(data);
				int headerlen = 0;
				if(header != NULL) headerlen = strlen(header);
 
				//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384247%28v=vs.85%29.aspx
				HttpSendRequestA(request, header, headerlen, data, datalen);
 
				//http://msdn.microsoft.com/en-us/library/windows/desktop/aa384350%28v=vs.85%29.aspx
				InternetCloseHandle(request);
			}
		}
		InternetCloseHandle(connect);
	}
	InternetCloseHandle(internet);
}
catch(...) {}
}

Usage:

//POST Request
char user[64] = "test123";
char pass[64] = "f4g5h6j7k8";
char data[1024];
char* posturi = "user=%s&pass=%s";
wsprintfA( data, posturi,  user, pass);
Request(POST, "localhost", "/testing/index.php", "Content-Type: application/x-www-form-urlencoded", data);
 
//---------------------------
 
//GET Request
char URL[1024];
char* geturi = "/testing/index.php?user=%s&pass=%s";
wsprintfA( URL, geturi, user, pass );
Request(GET, "localhost", URL, NULL, NULL);

Includes/Definitions:

//..
#include <Windows.h>
#include <WinInet.h>
#pragma comment (lib, "Wininet.lib")
#pragma comment (lib, "urlmon.lib")
#define POST 1
#define GET 0
Categories: C++ Tags: , , , , ,
%d bloggers like this: