Loading color scheme

How to Request HTTP(S) API or Page in MFC

Requesting HTTP resources in MFC may be a tricky part because you cannot use simple API as you would have used with files. You have to use special classes.

If you need to download a webpage, some file or make a REST API call using C++/MFC, you can use the following simple code sample:

 

BOOL RequestHTTP()
{
	BOOL bResult = FALSE;
	CInternetSession session;

	CHttpConnection* pConnection = NULL;
	try
	{
		pConnection = (CHttpConnection*)session.GetHttpConnection(_T("google.com"), (INTERNET_PORT)INTERNET_DEFAULT_HTTP_PORT);

		if (pConnection)
		{
			CHttpFile* pHTTPFile = NULL;

			pHTTPFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, _T("/"));
			if (pHTTPFile)
			{
				bResult = pHTTPFile->SendRequest(NULL, NULL, 0);
				if (bResult)
				{
					CString strResponse;
					char* pszBuff = new char[1025];
					int nRead = 0;
					while ((nRead = pHTTPFile->Read(pszBuff, 1024)) > 0)
					{
						pszBuff[nRead] = 0;
						strResponse += pszBuff;

					};

					delete[] pszBuff;

					wcout << LPCTSTR(strResponse) << endl;
					bResult = TRUE;
				}

				pHTTPFile->Close();

				delete pHTTPFile;
			}

			pConnection->Close();
			delete pConnection;
		}
	}
	catch (CInternetException * pEx)
	{
		pConnection = NULL;
		pEx->Delete();
	}

	session.Close();


	return bResult;
}

Get all interesting articles to your inbox
Please wait