两段代码解决一切
原代码,没有转存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;
}
评论