c++ 使用curl发送https POST请求并获取返回数据(包含appKey与appSecret)

借鉴连接:https://yq.aliyun.com/articles/629830?spm=a2c4e.11153940.blogcont630369.18.3dca5d3c1QHa9l

使用到libcurl库及openssl,

用VS2015写了个demo,记录一下,demo下载链接在文章末尾。

直接上代码:

#include <iostream>
#include <ostream>
#include <istream>
#include <stdlib.h>
#include <string.h>

#include "curl/curl.h"
#include <openssl/pem.h>
#include <openssl/hmac.h>

using namespace std;

size_t base64Encode(const void *data, int data_len, char *buffer)
{
	BIO *b64 = BIO_new(BIO_f_base64());
	BIO *bio = BIO_new(BIO_s_mem());

	bio = BIO_push(b64, bio);
	BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
	BIO_write(bio, data, data_len);
	BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, NULL);

	BUF_MEM *bptr = NULL;
	BIO_get_mem_ptr(bio, &bptr);

	size_t slen = bptr->length;
	memcpy(buffer, bptr->data, slen);
	buffer[slen] = '\0';

	BIO_free_all(bio);
	return slen;
}

int HmacEncode(const char * algo,
	const char * key, unsigned int key_length,
	const char * input, unsigned int input_length,
	string &strOutput, unsigned int &output_length) {
	const EVP_MD * engine = NULL;
	if (strcmp("sha512", algo) == 0) {
		engine = EVP_sha512();
	}
	else if (strcmp("sha256", algo) == 0) {
		engine = EVP_sha256();
	}
	else if (strcmp("sha1", algo) == 0) {
		engine = EVP_sha1();
	}
	else if (strcmp("md5", algo) == 0) {
		engine = EVP_md5();
	}
	else if (strcmp("sha224", algo) == 0) {
		engine = EVP_sha224();
	}
	else if (strcmp("sha384", algo) == 0) {
		engine = EVP_sha384();
	}
	else {
		cout << "Algorithm " << algo << " is not supported by this program!" << endl;
		return -1;
	}

	unsigned char* output = (unsigned char*)malloc(EVP_MAX_MD_SIZE);

	HMAC_CTX *ctx = HMAC_CTX_new();
	HMAC_Init_ex(ctx, key, strlen(key), engine, NULL);
	HMAC_Update(ctx, (unsigned char*)input, strlen(input));        // input is OK; &input is WRONG !!!

	HMAC_Final(ctx, output, &output_length);
	HMAC_CTX_free(ctx);

	strOutput = (char*)output;

	return 0;
}

// 将请求返回的数据写在本地文件
size_t HttpsReturnMsg(void* buffer, size_t size, size_t nmemb, void *stream)
{
	FILE *fptr = (FILE*)stream;
	fwrite(buffer, size, nmemb, fptr);
	return size*nmemb;
}

int main()
{
	CURL *curl;
	CURLcode res;

	curl_global_init(CURL_GLOBAL_ALL);
	curl = curl_easy_init();

	FILE* fp = fopen("e:/1.txt", "wb+");

	if (curl)
	{
		// 参考连接:https://yq.aliyun.com/articles/629830?spm=a2c4e.11153940.blogcont630369.18.3dca5d3c1QHa9l
		char Url[1024] = { 0 };
		sprintf_s(Url, "https://yq.aliyun.com/articles/629830?spm=a2c4e.11153940.blogcont630369.18.3dca5d3c1QHa9l");

		curl_slist *pList = NULL;
		pList = curl_slist_append(pList, "Accept:application/json, text/plain, */*");
		pList = curl_slist_append(pList, "Content-Type:application/json;charset=UTF-8");
		pList = curl_slist_append(pList, "X-Ca-Key:12345678");

		string appKey = "12345678";
		string appSecret = "TEST1234ABCD5678AAAA";
		string customHeaders = "x-ca-key:" + appKey + "\n";
		string httpHeaders = "POST\napplication/json, text/plain, */*\napplication/json;charset=UTF-8\n";
		string strNeedEncode = httpHeaders + customHeaders + "articles/629830?spm=a2c4e.11153940.blogcont630369.18.3dca5d3c1QHa9l";

		string strMac;
		unsigned int mac_length = 0;

		int ret = HmacEncode("sha256", appSecret.c_str(), appSecret.length(), strNeedEncode.c_str(), strNeedEncode.length(), strMac, mac_length);
		char *p = new char[128];
		memset(p, 0, 128);
		base64Encode(strMac.c_str(), mac_length, p);
		
		char strX_Ca_Signature[256] = { 0 };
		sprintf_s(strX_Ca_Signature, "X-Ca-Signature:%s", p);

		pList = curl_slist_append(pList, strX_Ca_Signature);
		pList = curl_slist_append(pList, "X-Ca-Signature-Headers:x-ca-key");
		curl_easy_setopt(curl, CURLOPT_HTTPHEADER, pList);

		curl_easy_setopt(curl, CURLOPT_URL, Url);
		curl_easy_setopt(curl, CURLOPT_POST, 1); // post req  
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, HttpsReturnMsg);	//对返回的数据进行操作的函数地址
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);					//这是HttpsReturnMsg的第四个参数值

		/* example.com is redirected, so we tell libcurl to follow redirection */
		curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);

		char strMsgBody[1024] = { 0 };
		sprintf_s(strMsgBody, 1024, "{\"name\":\"hhhh\",\"age\":\"12\"}");
		curl_easy_setopt(curl, CURLOPT_POSTFIELDS, strMsgBody);

		/* Perform the request, res will get the return code */
		res = curl_easy_perform(curl);

		/* Check for errors */
		if (res != CURLE_OK)
			fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));

		/* always cleanup */
		curl_easy_cleanup(curl);
	}
	curl_global_cleanup();

	return 0;
}

 

demo下载链接:https://download.csdn.net/download/m0_37684310/11199820

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: cURL 是一个在命令行下运行的开源工具和库,用来传输数据,支持多种协议,包括HTTP和HTTPS。通过cURL发送POST请求返回响应数据的步骤如下: 1. 引入cURL库。在C语言中,引入头文件`<curl/curl.h>`来使用cURL相关的函数和结构体。 2. 初始化cURL使用函数`curl_global_init(CURL_GLOBAL_ALL)`来初始化cURL。 3. 创建一个`CURL`指针,并通过`curl_easy_init()`函数进行初始化。 4. 设置请求的URL。使用`curl_easy_setopt()`函数,设置请求的URL,通过参数`CURLOPT_URL`指定URL地址。 5. 设置POST请求,并传递需要发送数据使用`curl_easy_setopt()`函数,通过参数`CURLOPT_POST`设置为1,表示使用POST方法发送请求。然后使用`curl_easy_setopt()`函数,通过参数`CURLOPT_POSTFIELDS`将需要发送数据传递给它。 6. 设置接收响应数据的回调函数。使用`curl_easy_setopt()`函数,通过参数`CURLOPT_WRITEFUNCTION`设置回调函数,用于接收响应数据。 7. 执行cURL请求使用`curl_easy_perform()`函数来执行cURL请求,并等待服务器响应。 8. 获取响应状态码。使用`curl_easy_getinfo()`函数,通过参数`CURLINFO_RESPONSE_CODE`来获取服务器返回的响应状态码。 9. 清理cURL相关资源。使用`curl_easy_cleanup()`函数来释放创建的cURL指针。 10. 清理cURL全局资源。使用`curl_global_cleanup()`函数来释放cURL全局资源。 这样就可以使用cURL发送POST请求返回响应数据了。根据实际需求,可以对步骤4和5进行调整来设置请求头信息、设置超时时间等。 ### 回答2: curl是一个广泛应用在命令行和脚本中的工具,可以用于发送HTTP请求获取返回的响应数据。在使用curl发送POST请求时,我们需要使用以下命令格式: ``` curl -X POST -d "参数1=值1&参数2=值2" URL ``` 其中,`-X POST`表示发送POST请求,`-d`表示要发送数据,以`参数=值`的形式进行传递,多个参数之间使用`&`连接,最后的URL为目标地址。 举例来说,如果我们要向`http://example.com/api`发送一个包含`username`和`password`的POST请求,并获取返回的响应数据,可以使用以下命令: ``` curl -X POST -d "username=admin&password=123456" http://example.com/api ``` 执行以上命令后,curl会向`http://example.com/api`发送一个POST请求请求数据为`username=admin&password=123456`,然后会返回请求的响应数据。 通过解析和处理返回数据,我们可以根据具体情况使用不同的方式进行操作,例如将响应保存到文件中、提取特定字段等。 总而言之,使用curl发送POST请求的步骤是:构造请求数据发送请求获取并处理响应数据。这样我们就可以在命令行中使用curl方便地发送POST请求获取响应数据。 ### 回答3: 使用cURL发送POST请求返回响应数据,可以通过以下的步骤实现: 第一步,包含必要的头文件: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> ``` 第二步,定义回调函数来处理响应数据: ```c size_t write_callback(void *ptr, size_t size, size_t nmemb, char *data) { memcpy(data, ptr, size * nmemb); return size * nmemb; } ``` 第三步,编写发送POST请求的函数: ```c char* send_post_request(char* url, char* post_data) { CURL *curl; CURLcode res; struct curl_slist *header_list = NULL; char *response_data = malloc(1); int response_size = 0; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(post_data)); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, response_data); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } curl_easy_cleanup(curl); } return response_data; } ``` 最后,可以通过以下方式调用函数发送POST请求获取响应数据: ```c int main() { char url[] = "http://example.com/api"; char post_data[] = "key1=value1&key2=value2"; char *response_data = send_post_request(url, post_data); printf("Response data: %s\n", response_data); free(response_data); return 0; } ``` 以上就是使用C语言和cURL发送POST请求返回响应数据的简单实现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值