C++ vs2017 http简单post/get请求

文章参考:https://blog.csdn.net/u014049599/article/details/79998674
一、编写“HttpRequest.h”文件

#pragma once
#include 
#include 

#include
#include 

class HttpRequest
{
public:
	HttpRequest(const std::string& ip, int port);
	~HttpRequest(void);

	// Http GET请求
	std::string HttpGet(std::string req);

	// Http POST请求
	std::string HttpPost(std::string req, std::string data);

	// 合成JSON字符串  string int
	static std::string genJsonString(std::string key, int value);
	// 合成JSON字符串  string  string
	static std::string genJsonString_string(std::map  mapRequest);

	// 分割字符串
	static std::vector split(const std::string &s, const std::string &seperator);

	// 根据key从Response获取Header中的内容
	static std::string getHeader(std::string respose, std::string key);
	//curl 发送请求
	//bool SendHttpUrl(std::string URL ,std::string strUrl);
	//解析json 字符串 获取指定返回值
	//static std::string HttpRequest::ParseJsonInfo(const std::string &strJsonInfo);

private:
	std::string         m_ip;
	int             m_port;
};

二、编写“HttpRequest.cpp”文件

#include "HttpRequest.h"
#include 
#include 

#include 


#pragma warning(disable : 4996)

#pragma comment(lib, "ws2_32.lib")

size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream);


HttpRequest::HttpRequest(const std::string& ip, int port) : m_ip(ip), m_port(port)
{
}


HttpRequest::~HttpRequest(void)
{
}

// Http GET请求
std::string HttpRequest::HttpGet(std::string req)
{
	std::string ret = ""; // 返回Http Response
	try
	{
		// 开始进行socket初始化
		WSADATA wData;
		::WSAStartup(MAKEWORD(2, 2), &wData);

		SOCKET clientSocket = socket(AF_INET, 1, 0);
		struct sockaddr_in ServerAddr = { 0 };
		ServerAddr.sin_addr.s_addr = inet_addr(m_ip.c_str());
		ServerAddr.sin_port = htons(m_port);
		ServerAddr.sin_family = AF_INET;
		int errNo = connect(clientSocket, (sockaddr*)&ServerAddr, sizeof(ServerAddr));
		if (errNo == 0)
		{
			//  "GET /[req] HTTP/1.1\r\n"  
			//  "Connection:Keep-Alive\r\n"
			//  "Accept-Encoding:gzip, deflate\r\n"  
			//  "Accept-Language:zh-CN,en,*\r\n"
			//  "User-Agent:Mozilla/5.0\r\n\r\n";
			std::string strSend = " HTTP/1.1\r\n"
				"Cookie:16888\r\n\r\n";
			strSend = "GET " + req + strSend;

			// 发送
			errNo = send(clientSocket, strSend.c_str(), strSend.length(), 0);
			if (errNo > 0)
			{
				//cout << "发送成功" << endl;
			}
			else
			{
				std::cout << "errNo:" << errNo << std::endl;
				return ret;
			}

			// 接收
			char bufRecv[3069] = { 0 };
			errNo = recv(clientSocket, bufRecv, 3069, 0);
			if (errNo > 0)
			{
				ret = bufRecv;// 如果接收成功,则返回接收的数据内容  
			}
			else
			{
				std::cout << "errNo:" << errNo << std::endl;
				return ret;
			}
		}
		else
		{
			errNo = WSAGetLastError();
			std::cout << "errNo:" << errNo << std::endl;
		}
		// socket环境清理
		::WSACleanup();
	}
	catch (...)
	{
		return "";
	}
	return ret;
}

// Http POST请求
std::string HttpRequest::HttpPost(std::string req, std::string data)
{
	std::string ret = ""; // 返回Http Response
	try
	{
		// 开始进行socket初始化;
		WSADATA wData;
		::WSAStartup(MAKEWORD(2, 2), &wData);

		SOCKET clientSocket = socket(AF_INET, 1, 0);
		struct sockaddr_in ServerAddr = { 0 };
		ServerAddr.sin_addr.s_addr = inet_addr(m_ip.c_str());
		//ServerAddr.sin_addr.s_addr = InetPton(m_ip.c_str());
		ServerAddr.sin_port = htons(m_port);
		ServerAddr.sin_family = AF_INET;
		int errNo = connect(clientSocket, (sockaddr*)&ServerAddr, sizeof(ServerAddr));
		if (errNo == 0)
		{
			// 格式化data长度
			char len[10] = { 0 };
			sprintf(len, "%d", data.length());
			std::string strLen = len;

			//  "POST /[req] HTTP/1.1\r\n"
			//  "Connection:Keep-Alive\r\n"
			//  "Accept-Encoding:gzip, deflate\r\n"
			//  "Accept-Language:zh-CN,en,*\r\n"
			//  "Content-Length:[len]\r\n"
			//  "Content-Type:application/x-www-form-urlencoded; charset=UTF-8\r\n"
			//  "User-Agent:Mozilla/5.0\r\n\r\n"
			//  "[data]\r\n\r\n";
			std::string strSend = " HTTP/1.1\r\n"
				"Cookie:16888\r\n"
				"Content-Type:application/x-www-form-urlencoded\r\n"
				"Charset:utf-8\r\n"
				"Content-Length:";
			strSend = "POST " + req + strSend + strLen + "\r\n\r\n" + data;

			// 发送
			errNo = send(clientSocket, strSend.c_str(), strSend.length(), 0);
			if (errNo > 0)
			{
				//cout<<"发送成功\n";
			}
			else
			{
				std::cout << "errNo:" << errNo << std::endl;
				return ret;
			}

			// 接收
			char bufRecv[3069] = { 0 };
			errNo = recv(clientSocket, bufRecv, 3069, 0);
			if (errNo > 0)
			{
				ret = bufRecv;// 如果接收成功,则返回接收的数据内容
			}
			else
			{
				std::cout << "errNo:" << errNo << std::endl;
				return ret;
			}
		}
		else
		{
			errNo = WSAGetLastError();
		}
		// socket环境清理
		::WSACleanup();
	}
	catch (...)
	{
		return "";
	}
	return ret;
}

// 合成JSON字符串 string int 
std::string HttpRequest::genJsonString(std::string key, int value)
{
	char buf[128] = { 0 };
	sprintf(buf, "{\"%s\":%d}", key.c_str(), value);
	std::string ret = buf;
	return ret;
}

// 合成JSON字符串  string  string 
std::string HttpRequest::genJsonString_string(std::map mapRequest)
{
	std::map::iterator iter;
	std::string ret = "{";
	char buf[128] = { 0 };
	for(iter = mapRequest.begin(); iter != mapRequest.end(); ++iter)
	{
		sprintf(buf, "\"%s\":\"%s\"", iter->first.c_str(), iter->second.c_str());
		ret = ret + buf + ",";
		//std::cout << iter->first << ":" << iter->second << std::endl;
	}
	ret = ret.substr(0, ret.length()-1);
	ret = ret + "}";
	/*char buf[128] = { 0 };
	sprintf(buf, "{\"%s\":%s}", key.c_str(), value.c_str());
	
	std::string ret = buf;*/
	std::cout << "json: " << ret << std::endl;
	return ret;
}

// 分割字符串
std::vector HttpRequest::split(const std::string &s, const std::string &seperator)
{
	std::vector result;
	typedef std::string::size_type string_size;
	string_size i = 0;

	while (i != s.size()) {
		// 找到字符串中首个不等于分隔符的字母
		int flag = 0;
		while (i != s.size() && flag == 0) {
			flag = 1;
			for (string_size x = 0; x < seperator.size(); ++x)
				if (s[i] == seperator[x]) {
					++i;
					flag = 0;
					break;
				}
		}

		// 找到又一个分隔符,将两个分隔符之间的字符串取出
		flag = 0;
		string_size j = i;
		while (j != s.size() && flag == 0) {
			for (string_size x = 0; x < seperator.size(); ++x)
				if (s[j] == seperator[x]) {
					flag = 1;
					break;
				}
			if (flag == 0)
				++j;
		}
		if (i != j) {
			result.push_back(s.substr(i, j - i));
			i = j;
		}
	}
	return result;
}

// 从Response中查找key对应的Header的内容
std::string HttpRequest::getHeader(std::string respose, std::string key)
{
	std::vector lines = split(respose, "\r\n");
	std::cout << "lines size: " << lines.size() << std::endl;
	for (int i = 0; i < lines.size(); i++)
	{
		std::vector line = split(lines[i], ": ");// 注意空格

		std::cout << "line[0]: " << line[0] << std::endl;
		if (line.size() >= 2 && line[0] == key)
		{
			return line[1];
		}
	}
	return "";
}

三、测试代码

// test4HTTP.cpp : 定义控制台应用程序的入口点。
//

#include "HttpRequest.h"
#include 
#include 

#include 

using namespace std;
//int _tmain(int argc, _TCHAR* argv[])
int main()
{
	HttpRequest httpReq("IP地址",端口);

	//std::string res = httpReq.HttpGet("/getsomething/");
	//std::cout << res << std::endl;
	//Sleep(1000);

	//构建json数据 
	std::map mapRequest;
	mapRequest.insert(pair("devno", "3333"));
	mapRequest.insert(pair("regtime", "2019-05-27 15:20:00"));
	mapRequest.insert(pair("diskno", "5555"));
	mapRequest.insert(pair("phoneno", "13855647894"));
	std::string request_string = HttpRequest::genJsonString_string(mapRequest);
	std::string res = httpReq.HttpPost("api接口", request_string);
	
	std::cout << res << std::endl;
	std::string str_status = res.substr(res.rfind("status") + 9, 1);
	//std::string str_status=httpReq.getHeader(res,"status");
	std::cout <<"str_status: "<< str_status << std::endl;
	if (stoi(str_status)==0) {
		std::cout << "regist success " << std::endl;

	}
	else {
		std::cout << "regist fail " << std::endl;
	}

	system("pause");
	return 0;
}

你可能感兴趣的:(post请求,get请求,C++,Http,socket)