c++工程中发送http请求的示例

#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 );
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值