C++使用curl發送post請求

發送post請求代碼如下:

#include<iostream>
#include<string>
#include<curl\curl.h>
using namespace std;
//get請求和post請求數據響應函數
size_t req_reply(void *ptr, size_t size, size_t nmemb, void *stream)
{
	//在註釋的裏面可以打印請求流,cookie的信息
	//cout << "----->reply" << endl;
	string *str = (string*)stream;
	//cout << *str << endl;
	(*str).append((char*)ptr, size*nmemb);
	return size * nmemb;
}
//http POST請求  
CURLcode curl_post_req(const string &url, const string &postParams, string &response)
{
	// curl初始化  
	CURL *curl = curl_easy_init();
	// curl返回值 
	CURLcode res;
	if (curl)
	{
		// set params
		//設置curl的請求頭
		struct curl_slist* header_list = NULL;
		header_list = curl_slist_append(header_list, "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko");
		header_list = curl_slist_append(header_list, "Content-Type:application/x-www-form-urlencoded; charset=UTF-8");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header_list);

		//不接收響應頭數據0代表不接收 1代表接收
		curl_easy_setopt(curl, CURLOPT_HEADER, 0);

		//設置請求爲post請求
		curl_easy_setopt(curl, CURLOPT_POST, 1);

		//設置請求的URL地址
		curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
		//設置post請求的參數
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postParams.c_str());

		//設置ssl驗證
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);

		//CURLOPT_VERBOSE的值爲1時,會顯示詳細的調試信息
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 0);

		curl_easy_setopt(curl, CURLOPT_READFUNCTION, NULL);

		//設置數據接收和寫入函數
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, req_reply);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);

		curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

		//設置超時時間
		curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 6);
		curl_easy_setopt(curl, CURLOPT_TIMEOUT, 6);

		// 開啓post請求
		res = curl_easy_perform(curl);
	}
	//釋放curl 
	curl_easy_cleanup(curl);
	return res;
}
int main()
{
	string url_post0 = "http://httpbin.org/post";
	string paramsLogin0 = "key1=value1&key2=value2";
	string resPost0;
	auto res3 = curl_post_req(url_post0, paramsLogin0, resPost0);
	if (res3 == CURLE_OK)
	{
		cout << resPost0 << endl;
	}

	getchar();
	return 0;
}

運行結果爲:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章