接口释义
使用libcurl实现http通信——get获取response
代码实现
size_t responseStr(void* ptr, size_t size, size_t nmemb, void *userdata) {
if (ptr == NULL || userdata == NULL || size == 0) {
return 0;
}
size_t realSize = size*nmemb;
std::string *str = (std::string*)userdata;
(*str).append((char*)ptr, realSize);
return realSize;
}
void postHttp() {
std::string data;
CURL *curl;
long status;
struct curl_slist* headers = NULL;
std::string str = "test";
curl = curl_easy_init();
// 设置url
curl_easy_setopt(curl, CURLOPT_URL, "https://*************");
headers = curl_slist_append(headers, "Content-Type: application/json");
// 设置 request header
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
// 设置不验证ssl证书
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
// 设置post请求方式
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// 设置request body
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, str.c_str());
// 设置request body 大小
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, str.size());
// 设置response回调函数
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, responseStr);
// 设置response 数据类型
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&data);
// 结束请求
CURLcode res = curl_easy_perform(curl);
// 获取response code
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &status);
curl_easy_cleanup(curl);
}