首先需要自己下载libcurl库,配置好相应的选项。
核心代码
CURL* curl = curl_easy_init(); //初始化 返回CURL指针
CURLcode state;
curl_easy_setopt(curl, CURLOPT_URL, myUrl.c_str());//CURLOPT_URL表示是http格式
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteDate);//WriteDate回调函数
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ResString);//ResString结果写入ResString中
state = curl_easy_perform(curl);//若连接成功则返回CURLE_OK 否则
if (state != CURLE_OK) { //连接失败
//do what you want to do
}
else {
//do what you want to do
}
curl_easy_cleanup();//必须有 和curl_easy_init();对应 防止内存泄漏
//回调函数
//回调函数 一旦有数据就会自动调用回调函数 内容写入ResInfo
int WriteDate(void *buffer, size_t sz, size_t nmemb, void *ResInfo)
{
string* psResponse = (string*)ResInfo;//强制转换
psResponse->append((char*)buffer, sz * nmemb); //sz*nmemb表示接受数据的多少
return sz * nmemb; //返回接受数据的多少
}