libcurl 接受完整数据

tech2023-11-04  98

首先了解一下基本的函数作用

1.       调用curl_global_init()初始化libcurl 2.       调用curl_easy_init()函数得到 easy interface型指针 3.       调用curl_easy_setopt()设置传输选项 4.       根据curl_easy_setopt()设置的传输选项,实现回调函数以完成用户特定任务 5.       调用curl_easy_perform()函数完成传输任务 6.       调用curl_easy_cleanup()释放内存

贴图看代码,这是百度NLP的接口例子

1、回调函数

 

static size_t callback(void *ptr, size_t size, size_t nmemb, void *stream) {

// 获取到的body存放在ptr中,先将其转换为string格式

 

std::string html_data(reinterpret_cast<const char*>(ptr), size * nmemb);

*(reinterpret_cast<std::ostringstream*>(stream)) << html_data;

 

return size * nmemb;

}

 

 

int unit_utterance(std::string &json_result, const std::string json_request_body,

const std::string &access_token) {

std::string url = get_utterance_url + "?access_token=" + access_token;

CURL *curl = NULL;

CURLcode result_code;

int is_success = 0;

curl = curl_easy_init();

if (curl) {

std::ostringstream writedata;

curl_easy_setopt(curl, CURLOPT_URL, url.data());

cout << "url "<<url.data() <<endl;

curl_easy_setopt(curl, CURLOPT_POST, 1);

curl_slist *headers = NULL;

headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");

curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_request_body.data());

curl_easy_setopt(p_curl, CURLOPT_WRITEDATA, &writedata);

curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);

result_code = curl_easy_perform(curl);

if (result_code != CURLE_OK) {

fprintf(stderr, "curl_easy_perform() failed: %s\n",

curl_easy_strerror(result_code));

cout << "error code "<<result_code << endl;

is_success = 1;

return is_success;

}

json_result = writedata.str();

//收集到完整的json数据

curl_easy_cleanup(curl);

is_success = 0;

} else {

fprintf(stderr, "curl_easy_init() failed.");

is_success = 1;

}

return is_success;

}

调用curl_easy_perform()函数表示完成传输任务

最新回复(0)