CURL发送HTTP请求获得Json数据串保存在本地(linux 下 C++ 编程)

最近在做一个项目,要用到Json和Curl请求。要求是这样的

我需要用CURL + 目的IP地址来向目的地址发送一个HTTP请求,请求会返回一个Json的字符串,我将其获得保存在本地用来使用;

我就直接上代码了,具体就不解释了,仅供大家参考

#include<iostream>
#include<string>
#include<curl/curl.h>
#include<json/json.h>
#include<fstream>
#define filemax 2048
#define CDN_num 1024
using namespace std;
size_t get_data(void*prt,size_t size, size_t nmemb, FILE * stream)
{
		size_t written = fwrite(prt,size,nmemb,stream);
			return written;
}


struct CDN_Info
{
	string name;
	string IP;
	string APP;
	string StreamName;
	int Link_num;
};

int main()
{
	CDN_Info CDN_Mess[CDN_num];
	int i=0;
	FILE* fp;
        const char* api_url="192.168.1.107/getclient";
	CURLcode res;
	CURL* curl=curl_easy_init();
	char outfile[filemax]="Temp.json";
	fp = fopen(outfile,"wb");
	curl_easy_setopt(curl,CURLOPT_URL,api_url);
	curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,get_data);
	curl_easy_setopt(curl,CURLOPT_WRITEDATA,fp);
	res=curl_easy_perform(curl);
	if (res!=CURLE_OK)
	{
		perror("Curl error");
		return 1;
	}
	curl_easy_cleanup(curl);
	fclose(fp);
	
	Json::Reader reader;
	Json::Value root;
	
	ifstream is;
	is.open("Temp.json",ios::out);
    if (!reader.parse(is,root))
	{
		return 1;
	}
	for (Json::Value::iterator idx = root.begin();idx != root.end();idx++)
	{
		CDN_Mess[i].name=root[i]["name"].asString();
		CDN_Mess[i].IP=root[i]["url"].asString();
		CDN_Mess[i].APP=root[i]["app"].asString();
		CDN_Mess[i].StreamName=root[i]["stream"].asString();
    	        CDN_Mess[i].Link_num=root[i]["client"].asInt();
		i++;
	}
}


猜你喜欢

转载自blog.csdn.net/liaoxuda_edu/article/details/77512167