https://curl.haxx.se/
https://curl.haxx.se/libcurl/c/example.html官网的例子
#include
#include
#include
using namespace std;
struct WriteThis{
const char* readptr;
long sizeleft;
};
size_t readData(void* buffer,size_t size, size_t nmemb, void* userdata)
{
struct WriteThis* data = (struct WriteThis*)userdata;
if(data == NULL)
{
return -1;
}
if(size*nmemb < 1)
{
return 0;
}
if(data->sizeleft)
{
*(char*)buffer = data->readptr[0];
data->readptr++;
data->sizeleft--;
return 1;
}
return 0;
}
//buffer为接收到的数据,size*nmemb为接收的数据大小,userdata返回的数据指定的输出流
static size_t OnWriteData(void* buffer, size_t size, size_t nmemb, void* userdata)
{
string* str = dynamic_cast((string *)userdata);
if( NULL == str || NULL == buffer )
{
return -1;
}
char* pData = (char*)buffer;
str->append(pData, size * nmemb);
return nmemb;
}
bool get()
{
string body;
string head;
CURL* curl;
CURLcode res;
FILE* file = fopen("./resp.html","wb");
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers,"Accept:Agent-000");
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);
curl_easy_setopt(curl,CURLOPT_URL,"www.baidu.com");
//test
curl_easy_setopt(curl,CURLOPT_READFUNCTION,readData);
//如果没有注册CURLOPT_WRITEDATA和CURLOPT_WRITEFUNCTION测执行默认的回调函数(打印到控制台)
// curl_easy_setopt(curl,CURLOPT_HEADERDATA,file);//存入本地文件 对接收的数据处理方式 *****方式1******
// curl_easy_setopt(curl,CURLOPT_WRITEDATA,file);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,OnWriteData); /// ******方式2*********
curl_easy_setopt(curl,CURLOPT_WRITEDATA,(void*)&body);//读入string
curl_easy_setopt(curl,CURLOPT_ACCEPT_ENCODING,"gzip");
res = curl_easy_perform(curl);
if(res != 0)
{
curl_slist_free_all(headers);
}
}else{
}
if(!body.empty())
{
cout << body << endl;
}else{
cout << "resp empty" << endl;
}
fclose(file);
curl_easy_cleanup(curl);
return true;
}
bool post()
{
string resp_data;
char data[] = "{\"content\":\"hello world\"}";
struct WriteThis pooh;
pooh.readptr = data;
pooh.sizeleft = (long)strlen(data);
CURL* curl;
CURLcode res;
curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl,CURLOPT_URL,"www.baidu.com");
curl_easy_setopt(curl,CURLOPT_POST,1);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,OnWriteData);
curl_easy_setopt(curl,CURLOPT_WRITEDATA,(void*)&resp_data);
curl_easy_setopt(curl,CURLOPT_READFUNCTION,readData); //使用定制的read function
curl_easy_setopt(curl,CURLOPT_READDATA,&pooh);
curl_easy_setopt(curl,CURLOPT_POSTFIELDSIZE,pooh.sizeleft);//不设定size,注册的read function不会被执行
//curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);//使用默认的read function的方式
//curl_easy_setopt(curl,CURLOPT_POSTFIELDSIZE,strlen(data));
//curl_easy_setopt(curl,CURLOPT_TIMEOUT,1);
res = curl_easy_perform(curl);
}
if(res != 0){}
curl_easy_cleanup(curl);
return true;
}
int main()
{
//get();
post();
return 0;
}