curl发送Json格式http请求

//将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("");	//异常返回空字符串
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值