概述
//将response写入stream
size_t write_data_to_stream(void* ptr, size_t size, size_t nmemb, void* stream)
{
string data((const char*)ptr, (size_t)size * nmemb);
*((stringstream*)stream) << data << endl;
return size * nmemb;
}
string SendHttpJsonRequest(const string& url, const string& send_data, const int& time_out, int& http_code)
{
CURL *curl;
stringstream out;
//HTTP报文头
struct curl_slist* headers = NULL;
try
{
curl = curl_easy_init();
if (curl)
{
/* First set the URL that is about to receive our POST. */
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
//构建HTTP报文头
headers = curl_slist_append(headers, "Content-Type:application/json;charset=UTF-8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
/* Now specify we want to POST data */
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/* we want to use our own write function */
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_to_stream);
/* pointer to pass to our write function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
/* get verbose debug output please */
curl_easy_setopt(curl, CURLOPT_VERBOSE, 0); //no debug
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, send_data.c_str());
/* Set the expected POST size. If you want to POST large amounts of data,
consider CURLOPT_POSTFIELDSIZE_LARGE */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, send_data.size());
curl_easy_setopt(curl, CURLOPT_TIMEOUT, time_out);
/* Perform the request, http_code will get the return http status */
CURLcode code = curl_easy_perform(curl);
if (code == CURLE_OK)
{
code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
if ((CURLE_OK != code) || !http_code)
http_code = -1;
}
/* free the list again */
curl_slist_free_all(headers);
/* always cleanup */
curl_easy_cleanup(curl);
}
return out.str();
}
catch (std::exception &e)
{
LogError << "[SendHttpJsonRequest] exception: " << e.what();
return string(""); //异常返回空字符串
}
}
最后
以上就是耍酷飞鸟为你收集整理的curl发送Json格式http请求的全部内容,希望文章能够帮你解决curl发送Json格式http请求所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复