【C++】使用 curl 库配置 HTTP 的 Post/Get 请求响应数据(封装一个简单类)

2023.7.18 Update: 【LibCurl】C++使用libcurl实现HTTP POST和GET

要想使用 LibCURL 库,首先需配置 CURL 库

参考链接:【C++开源库】Windows 下编译 libcurl 库

// 测试代码
#include <iostream>
using namespace std;;
int main()
{
    curl_easy_init();
    return 0;
}

// 没报错即配置成功

下面是上传json数据代码(下面以字符串为例子)

我手动拼接json字符串就不用配置json库了(配置json库在下面)

#include <curl/curl.h>
#include <string>
#include <exception>
#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
	//下面是json数据格式
	char szJsonData[1024];
	memset(szJsonData, 0, sizeof(szJsonData));
	string aa = "123";
	string strJson = "{";
	strJson += ""hex" : "" + aa + "",";
	strJson += ""aa" : "123",";
	strJson += ""bb" : "123",";
	strJson += ""cc" : "123"";
	strJson += "}";
	strcpy(szJsonData, strJson.c_str());
	
	try
	{
		CURL *pCurl = NULL;
		CURLcode res;
		// In windows, this will init the winsock stuff
		curl_global_init(CURL_GLOBAL_ALL);

		// get a curl handle
		pCurl = curl_easy_init();
		if (NULL != pCurl)
		{
			// 设置超时时间为1秒
			curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1);

			// First set the URL that is about to receive our POST. 
			// This URL can just as well be a 
			// https:// URL if that is what should receive the data.
			curl_easy_setopt(pCurl, CURLOPT_URL, "your URL");
		

			// 设置http发送的内容类型为JSON
			curl_slist *plist = curl_slist_append(NULL,
				"Content-Type:application/json;charset=UTF-8");
			curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);

			// 设置要POST的JSON数据
			curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, szJsonData);

			// Perform the request, res will get the return code 
			res = curl_easy_perform(pCurl);
			// Check for errors
			if (res != CURLE_OK)
			{
				printf("curl_easy_perform() failed:%s\n", curl_easy_strerror(res));
			}
			// always cleanup
			curl_easy_cleanup(pCurl);
		}
		curl_global_cleanup();
	}
	catch (std::exception &ex)
	{
		printf("curl exception %s.\n", ex.what());
	}

	return 0;
}

配置 JSON 第三方库

  • cJSON

    git clone https://github.com/DaveGamble/cJSON.git
    # 拉取最新的 cJSON 版本
    # 把文件夹下的 cJSON.h 和 cJSON.c 文件放在自己的项目文件夹下即可
    
  • jsoncpp

    参考文章:https://www.cnblogs.com/tudou/p/14957646.html

下面是测试代码:

#include <iostream>
#include "json/json.h"
using namespace std;
int main()
{
	string aa = "123";
	//Json::Value jsonRoot; //定义根节点
	Json::Value jsonItem; //定义一个子对象
	jsonItem["hexImage"] =aa; //添加数据

	//jsonRoot.append(jsonItem);
	//jsonItem.clear(); //清除jsonItem

	//jsonRoot["item"] = jsonItem;
	cout << jsonItem.toStyledString() << endl; //输出到控制台

	//解析字符串--输入json字符串,指定解析键名,得到键的值。
	string str=jsonItem.toStyledString();
	Json::Reader reader;
	Json::Value root; //定义一个子对象
	if (reader.parse(str, root))
	{
		string jsstr= root["hexImage"].asString();
		cout << "jsstr:" << jsstr<< endl;
	}
	return 0;
}

下面给一个封装curl的类给大家使用。需要根据你需要的版本进行编译对应x86和x64

博主使用的是 VS2013 + x86 版本

// 头文件
#pragma once
#include <iostream>

using namespace std;
class Httpcurl
{
public:

	//初始化curl库
	void initcurl();

	//释放curl库
	void closecurl();
	
	//接口请求
	std::string requesthttp(std::string sendstr, std::string url);
};
// 实现文件
#include "Httpcurl.h"
#include <curl/curl.h>

//回调函数
size_t http_data_writer(void* data, size_t size, size_t nmemb, void* content)
{
	long totalSize = size * nmemb;
	//强制转换
	std::string* symbolBuffer = (std::string*)content;
	if (symbolBuffer)
	{
		symbolBuffer->append((char *)data, ((char*)data) + totalSize);
	}
	//cout << "symbolBuffer:" << symbolBuffer << endl;
	//返回接受数据的多少
	return totalSize;
}

void Httpcurl::initcurl()
{
	//初始化curl库
	curl_global_init(CURL_GLOBAL_ALL);
}

void Httpcurl::closecurl()
{
	//释放内存,curl库
	curl_global_cleanup();
}

//输入请求json,返回string
std::string Httpcurl::requesthttp(std::string sendstr, std::string url)
{
	std::string strData;
	CURL *pCurl = NULL;
	CURLcode res;
	// 获得一个句柄
	pCurl = curl_easy_init();
	if (NULL != pCurl)
	{
		// 设置超时时间为1秒
		curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1);

		//设置url
		curl_easy_setopt(pCurl, CURLOPT_URL, const_cast<char *>(url.c_str()));

		// 设置http发送的内容类型为JSON格式
		curl_slist *plist = curl_slist_append(NULL,
			"Content-Type:application/json;charset=UTF-8");
		curl_easy_setopt(pCurl, CURLOPT_HTTPHEADER, plist);

		// 设置要POST的JSON数据
		curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, sendstr.c_str());

		// 设置回调函数
		curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, http_data_writer);
		//设置写数据

		curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, (void*)&strData);

		// 请求成功
		res = curl_easy_perform(pCurl);

		// Check for errors
		if (res != CURLE_OK)
		{
			printf("请求失败\n");
			return "error";
		}
		else
		{
			cout << "请求成功" << endl;
		}

		// always cleanup
		curl_easy_cleanup(pCurl);
	}
	return strData;
}
// main.cpp
#include <iostream>
#include "json/json.h"
#include "Httpcurl.h"
using namespace std;



int main(int argc, char *argv[])
{

	Json::Value jsonItem; //定义一个子对象
	jsonItem["aaa"] = "123"; //添加数据
	jsonItem["bbb"] = "456"; //添加数据

	string str = jsonItem.toStyledString();

	string url = "http://localhost:8080/test";

	Httpcurl httpcurl;
	httpcurl.initcurl();
	cout << httpcurl.requesthttp(str,url) << endl;
	httpcurl.closecurl();
	
	getchar();

	return 0;
}

响应什么大家自己用web写个接口测试吧。我这里是获取了它返回的数据。

也可以根据返回的状态码进行判断,是否接收成功。根据实际要求操作。

posted @ 2023-07-17 16:43  Koshkaaa  阅读(416)  评论(0编辑  收藏  举报