#include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include "Wininet.h"
#pragma comment(lib,"Wininet.lib")
extern std::string g_remotIp = "192.168.1.100";
extern int g_remotPort = 8080;
extern std::string g_requestString = "/cfg/test.html?message:";
extern std::string g_requestMethod = "POST";
bool sendHttpRequest(const std::string &sEvent)
{
if ( g_remotIp.empty() || (g_remotPort == 0) || g_requestString.empty() || g_requestMethod.empty() )
{
std::cout << " sendHttpRequest failed! paremeter is invalied! " << std::endl;
return false;
}
HINTERNET hInternet, hConnect, hRequest;
BOOL bRet;
std::string strResponse;
WCHAR wCharStrTemp[256];
char2wchar("User-Agent", wCharStrTemp, 256);
hInternet = (HINSTANCE)InternetOpen(wCharStrTemp, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (!hInternet)
goto Ret0;
WCHAR wCharStrRemotIp[256];
char2wchar(const_cast<char*>(g_remotIp.c_str()), wCharStrRemotIp, 256);
char2wchar("HTTP/1.1", wCharStrTemp, 256);
hConnect = (HINSTANCE)InternetConnect(hInternet, wCharStrRemotIp, g_remotPort, NULL, wCharStrTemp, INTERNET_SERVICE_HTTP, 0, 0);
if (!hConnect)
goto Ret0;
WCHAR wCharMethod[256];
WCHAR wCharRequestMsg[256];
g_requestString += sEvent;
char2wchar(const_cast<char*>(g_requestMethod.c_str()), wCharMethod, 256);
char2wchar(const_cast<char*>(g_requestString.c_str()), wCharRequestMsg, 256);
hRequest = (HINSTANCE)HttpOpenRequest(hConnect, wCharMethod, wCharRequestMsg, wCharStrTemp, NULL, NULL, INTERNET_FLAG_RELOAD, 0);
if (!hRequest)
goto Ret0;
bRet = HttpAddRequestHeaders(hRequest,"Content-Type: application/x-www-form-urlencoded",Len(FORMHEADERS),HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD);
if(!bRet)
goto Ret0;
bRet = HttpSendRequest(hRequest, NULL, 0, NULL, 0);
unsigned long recvLen = 0;
while (TRUE)
{
char cReadBuffer[1024 * 10] = { 0 };
unsigned long lNumberOfBytesRead;
bRet = InternetReadFile(hRequest, cReadBuffer, sizeof(cReadBuffer) - 1, &lNumberOfBytesRead);
if (!bRet || !lNumberOfBytesRead)
break;
cReadBuffer[lNumberOfBytesRead] = 0;
strResponse = strResponse + cReadBuffer;
recvLen += lNumberOfBytesRead;
}
Ret0:
if (hRequest)
InternetCloseHandle(hRequest);
if (hConnect)
InternetCloseHandle(hConnect);
if (hInternet)
InternetCloseHandle(hInternet);
std::cout << "Recved httpServer msg: " << strResponse << " , recved len: " << recvLen << std::endl;
return true;
}
int main()
{
std::string sendMsg = "hello world"; // send msg is: 192.168.1.100/cfg/test.html?message:hello world
sendHttpRequest( sendMsg );
}
c++工程中发送http请求的示例
最新推荐文章于 2024-04-23 17:07:03 发布