首页 C/C++修行正文

C++ libcurl的CURLcode转存为string类型

欲儿 C/C++修行 2019-08-19 612 0

两段代码解决一切



原代码,没有转存string



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

int main()
{
	system("chcp 65001");//很多时候,中文乱码,加上就行了
	CURL *hnd = curl_easy_init();

	curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET");
	curl_easy_setopt(hnd, CURLOPT_URL, "http://www.anyuer.club");

	struct curl_slist *headers = NULL;
	headers = curl_slist_append(headers, "Postman-Token: c3ec6cd6-2406-46cb-a7ee-e2c7b228f40d");
	headers = curl_slist_append(headers, "cache-control: no-cache");
	curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);

	CURLcode ret = curl_easy_perform(hnd);

	while (true);
	return 0;
}







改进后代码,其实问题的关键在于你得加一个回调函数



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

size_t WriteCallback(char *contents, size_t size, size_t nmemb, void *userp)
{
	((std::string*)userp)->append((char*)contents, size * nmemb);
	return size * nmemb;
}

int main()
{
	system("chcp 65001");//很多时候,中文乱码,加上就行了
	CURL *hnd = curl_easy_init();
	string readBuffer;
	curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "GET");
	curl_easy_setopt(hnd, CURLOPT_URL, "http://www.anyuer.club");

	struct curl_slist *headers = NULL;
	headers = curl_slist_append(headers, "Postman-Token: c3ec6cd6-2406-46cb-a7ee-e2c7b228f40d");
	headers = curl_slist_append(headers, "cache-control: no-cache");
	curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);
	curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, WriteCallback);
	curl_easy_setopt(hnd, CURLOPT_WRITEDATA, &readBuffer);

	CURLcode ret = curl_easy_perform(hnd);
	cout  << readBuffer << endl;

	while (true);
	return 0;
}


版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

评论