C++开发示例
更新时间:2023-06-07
我们在写下边的示例代码时,为了简单清楚,便于理解,忽略了一些错误处理,用户基于以下示例开发的时候,可以自行补齐。
一些公共函数
首先我们这里定义一个HttpRequest
结构,后续的 demo 中我们会使用到这个结构。
C++
1struct HttpRequest {
2 HttpRequest() {
3 // 只支持ContentType为json
4 headers["Content-Type"] = "application/json";
5 }
6 std::string method;
7 std::string url;
8 std::string path;
9 std::string body;
10 std::map<std::string, std::string> headers;
11 std::map<std::string, std::string> params;
12};
接下来是一些公共的函数。
C++
1// 时间戳转为公有云utc时间串的函数
2// 例如:1535904000 转换为 2018-09-02T16:00:00Z
3inline std::string timestamp_to_utc(time_t timestamp) {
4 struct tm* timeinfo = gmtime(×tamp);
5 const int buf_size = 32;
6 char buf[buf_size];
7 strftime(buf, buf_size, "%FT%TZ", timeinfo);
8 return std::string(buf);
9}
10
11// curl回调方法,用于读出返回的content,即body内容
12size_t content_data(void* buffer, size_t size, size_t nmemb, void* userp) {
13 *((std::string*)userp) = *((std::string*)userp) +
14 std::string((const char*)buffer, size * nmemb);
15 return size * nmemb;
16}
17// curl回调方法,用于读出返回的header
18size_t header_data(void* buffer, size_t size, size_t nmemb, void* userp) {
19 *((std::string*)userp) = *((std::string*)userp) +
20 std::string((const char*)buffer, size * nmemb);
21 return size * nmemb;
22}
23
24// 发送http请求
25void execute_curl_http_request(const HttpRequest& http_request) {
26 // 使用curl发送请求
27 CURL* curl = curl_easy_init();
28 struct curl_slist* curl_headers = NULL;
29 // 填充header
30 for (auto const& item : http_request.headers) {
31 std::string header = item.first + ":" + item.second;
32 curl_headers = curl_slist_append(curl_headers, header.c_str());
33 }
34 // 拼接Url
35 std::string url = http_request.url;
36 url.append(http_request.path);
37 // 设置Url
38 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
39 // 设置headers
40 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, curl_headers);
41 // 设置method
42 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, http_request.method.c_str());
43
44 if (!http_request.body.empty()) {
45 // 设置body
46 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, http_request.body.c_str());
47 }
48
49 // 设置返回的header,content
50 // 如果你不需要解析header和content,则不需要做此设置,返回的content也会直接打印到标准输出
51 std::string header;
52 std::string content;
53 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, content_data);
54 curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_data);
55 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &content);
56 curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header);
57 // 发送请求
58 curl_easy_perform(curl);
59 // 解析http返回码
60 long http_code = -1;
61 curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
62 // 清理curl
63 curl_easy_cleanup(curl);
64 // 打印返回的header内容
65 printf("query response header: %s.\n", header.c_str());
66 // 打印返回的content内容,为json格式,具体可参考api文档
67 // 如果你需要对返回的内容做下一步处理,可以将此content按json格式解析后作为后续使用
68 printf("query result: %s.\n", content.c_str());
69}
生成认证字符串
在访问云数据库 TableStorage 时,每个访问都需要使用用户的 AK/SK 生成认证字符串来进行身份认证,我们这里给出了 C++实现的 demo,其他语言的实现可以参考百度智能云鉴权认证机制和百度智能云认证字符串生成代码示例。
我们在这里定义了一个根据 HttpRequest 生成认证字符串的函数,具体实现见本页最下方的百度智能云认证字符串 C++ 实现。
C++
1std::string gen_authorization(const HttpRequest& request, int timestamp);
创建 Instance
当用户开通云数据库 TableStorage 服务后,需要先创建一个 instance。
C++
1void create_instance() {
2 // 将创建名为ins_demo的instance
3 const std::string instance_name = "ins_demo";
4 // 初始化HttpRequest
5 HttpRequest http_request;
6 http_request.url = "http://bts.bd.baidubce.com";
7 // 方法为PUT表示创建资源
8 http_request.method = "PUT";
9 http_request.path = "/v1/instance/" + instance_name;
10 // 获取当前时间戳
11 time_t timestamp = time(NULL);
12 // 注意Http请求中的x-bce-date与生成认证字符串的时间需一致
13 http_request.headers["x-bce-date"] = timestamp_to_utc(timestamp);
14 http_request.headers["Host"] = "bts.bd.baidubce.com";
15 http_request.headers["Authorization"] = gen_authorization(http_request, timestamp);
16
17 execute_curl_http_request(http_request);
18}
创建 Table
用户在创建好 Instance 后,就可以在 Instance 中创建表了,下边的示例是创建一张默认结构的表,如果用户对于表结构有特别需求,可参考API 参考增加参数。
C++
1void create_table() {
2 // 将在ins_demo中创建名为table_demo的table
3 const std::string instance_name = "ins_demo";
4 const std::string table_name = "table_demo";
5 // 初始化HttpRequest
6 HttpRequest http_request;
7 http_request.url = "http://bts.bd.baidubce.com";
8 // 方法为PUT表示创建资源
9 http_request.method = "PUT";
10 http_request.path = "/v1/instance/" + instance_name + "/table/" + table_name;
11 // 获取当前时间戳
12 time_t timestamp = time(NULL);
13 // 注意Http请求中的x-bce-date与生成认证字符串的时间需一致
14 http_request.headers["x-bce-date"] = timestamp_to_utc(timestamp);
15 http_request.headers["Host"] = "bts.bd.baidubce.com";
16 http_request.headers["Authorization"] = gen_authorization(http_request, timestamp);
17
18 execute_curl_http_request(http_request);
19}
向 Table 写入数据
用户创建好 Table 后,就可以向 Table 写入数据。
C++
1void insert() {
2 // 将向ins_demo中的表table_demo中写入一行数据
3 const std::string instance_name = "ins_demo";
4 const std::string table_name = "table_demo";
5 // 初始化HttpRequest
6 HttpRequest http_request;
7 http_request.url = "http://bts.bd.baidubce.com";
8 // 方法为PUT表示创建资源,即写入数据
9 http_request.method = "PUT";
10 http_request.path = "/v1/instance/" + instance_name + "/table/" + table_name + "/row";
11 // 拼接写入的数据,为json格式,并且数据要经过UrlEncode
12 // 写入rowkey(主键)为"www.baidu.com/0"的两列数据:col1,值为"val1",col2,值为"val2"
13 http_request.body =
14 "{"
15 "\"rowkey\":\"www.baidu.com%2F0\","
16 "\"cells\":["
17 "{"
18 "\"column\":\"col1\","
19 "\"value\":\"val1\""
20 "},"
21 "{"
22 "\"column\":\"col2\","
23 "\"value\":\"val2\""
24 "}"
25 "]}";
26 // 获取当前时间戳
27 time_t timestamp = time(NULL);
28 // 注意Http请求中的x-bce-date与生成认证字符串的时间需一致
29 http_request.headers["x-bce-date"] = timestamp_to_utc(timestamp);
30 http_request.headers["Host"] = "bts.bd.baidubce.com";
31 http_request.headers["Content-Length"] = std::to_string(http_request.body.size());
32 http_request.headers["Authorization"] = gen_authorization(http_request, timestamp);
33
34 execute_curl_http_request(http_request);
35}
从 Table 读取数据
一般来说,读取数据时,用户需要解析所读取的内容,所以我们在读示例里增加了 curl 获取返回内容的代码。用户可以指定 rowkey 从 Table 中读取数据。
C++
1void query() {
2 // 将向ins_demo中的table_demo读取一条数据
3 const std::string instance_name = "ins_demo";
4 const std::string table_name = "table_demo";
5 // 初始化HttpRequest
6 HttpRequest http_request;
7 http_request.url = "http://bts.bd.baidubce.com";
8 // 方法为GET表示获取资源
9 http_request.method = "GET";
10 http_request.path = "/v1/instance/" + instance_name + "/table/" + table_name + "/row";
11 // 拼接单条读请求,为json格式,并且数据要经过UrlEncode
12 // 读取rowkey(主键)为"www.baidu.com/0"的两列数据:col1和col2
13 // 如果需要读整行数据,则只需要设置rowkey即可
14 http_request.body =
15 "{"
16 "\"rowkey\":\"www.baidu.com%2F0\","
17 "\"cells\":["
18 "{"
19 "\"column\":\"col1\""
20 "},"
21 "{"
22 "\"column\":\"col2\""
23 "}"
24 "]}";
25
26 // 获取当前时间戳
27 time_t timestamp = time(NULL);
28 // 注意Http请求中的x-bce-date与生成认证字符串的时间需一致
29 http_request.headers["x-bce-date"] = timestamp_to_utc(timestamp);
30 http_request.headers["Host"] = "bts.bd.baidubce.com";
31 http_request.headers["Content-Length"] = std::to_string(http_request.body.size());
32 http_request.headers["Authorization"] = gen_authorization(http_request, timestamp);
33
34 execute_curl_http_request(http_request);
35}
用户可以范围扫描数据。
C++
1void scan() {
2 // 将向ins_demo中的table_demo读取数据
3 const std::string instance_name = "ins_demo";
4 const std::string table_name = "table_demo";
5 // 初始化HttpRequest
6 HttpRequest http_request;
7 http_request.url = "http://bts.bd.baidubce.com";
8 // 方法为GET表示获取资源
9 http_request.method = "GET";
10 http_request.path = "/v1/instance/" + instance_name + "/table/" + table_name + "/rows";
11 // 拼接范围读请求,为json格式,并且数据要经过UrlEncode
12 // 读取rowkey(主键)范围为[www.baidu.com/0, www.baidu.com/9)数据,并且读取其中两列:col1和col2
13 // 注意includeStart和includeStop为区间的开闭,本示例中,区间为前闭后开
14 // limit为1表示只返回第一行这个区间内的数据
15 // rowkey区间和其它参数,用户可以参考api文档,按需配置
16 http_request.body =
17 "{"
18 "\"startRowkey\":\"www.baidu.com%2F0\","
19 "\"includeStart\":true,"
20 "\"stopRowkey\":\"www.baidu.com%2F9\","
21 "\"includeStop\":false,"
22 "\"selector\":["
23 "{"
24 "\"column\":\"col1\""
25 "},"
26 "{"
27 "\"column\":\"col2\""
28 "}],"
29 "\"limit\":1"
30 "}";
31 // 获取当前时间戳
32 time_t timestamp = time(NULL);
33 // 注意Http请求中的x-bce-date与生成认证字符串的时间需一致
34 http_request.headers["x-bce-date"] = timestamp_to_utc(timestamp);
35 http_request.headers["Host"] = "bts.bd.baidubce.com";
36 http_request.headers["Content-Length"] = std::to_string(http_request.body.size());
37 http_request.headers["Authorization"] = gen_authorization(http_request, timestamp);
38
39 execute_curl_http_request(http_request);
40}
删除 Table 中数据
用户也可以指定 rowkey 删除 Table 中的某行数据。
C++
1void remove() {
2 // 将删除ins_demo中的表table_demo中的一行数据
3 const std::string instance_name = "ins_demo";
4 const std::string table_name = "table_demo";
5 // 初始化HttpRequest
6 HttpRequest http_request;
7 http_request.url = "http://bts.bd.baidubce.com";
8 // 方法为DELETE表示删除资源
9 http_request.method = "DELETE";
10 http_request.path = "/v1/instance/" + instance_name + "/table/" + table_name + "/row";
11 // 拼接写入的数据,为json格式,并且数据要经过UrlEncode
12 // 删除rowkey(主键)为"www.baidu.com/0"的两列数据:col1,值为"val1",col2,值为"val2"
13 // 如果要将整行,则不需要设置cells,只需设置rowkey即可
14 http_request.body =
15 "{"
16 "\"rowkey\":\"www.baidu.com%2F0\","
17 "\"cells\":["
18 "{"
19 "\"column\":\"col1\","
20 "\"value\":\"val1\""
21 "},"
22 "{"
23 "\"column\":\"col2\","
24 "\"value\":\"val2\""
25 "}"
26 "]}";
27 // 获取当前时间戳
28 time_t timestamp = time(NULL);
29 // 注意Http请求中的x-bce-date与生成认证字符串的时间需一致
30 http_request.headers["x-bce-date"] = timestamp_to_utc(timestamp);
31 http_request.headers["Host"] = "bts.bd.baidubce.com";
32 http_request.headers["Content-Length"] = std::to_string(http_request.body.size());
33 http_request.headers["Authorization"] = gen_authorization(http_request, timestamp);
34
35 execute_curl_http_request(http_request);
36}
删除 Table
用户如果不再使用某张表,则可将其删除,其中的数据也会清理。
C++
1void drop_table() {
2 // 将删除ins_demo中名为table_demo的table
3 const std::string instance_name = "ins_demo";
4 const std::string table_name = "table_demo";
5 // 初始化HttpRequest
6 HttpRequest http_request;
7 http_request.url = "http://bts.bd.baidubce.com";
8 // 方法为DELETE表示删除资源
9 http_request.method = "DELETE";
10 http_request.path = "/v1/instance/" + instance_name + "/table/" + table_name;
11 // 获取当前时间戳
12 time_t timestamp = time(NULL);
13 // 注意Http请求中的x-bce-date与生成认证字符串的时间需一致
14 http_request.headers["x-bce-date"] = timestamp_to_utc(timestamp);
15 http_request.headers["Host"] = "bts.bd.baidubce.com";
16 http_request.headers["Authorization"] = gen_authorization(http_request, timestamp);
17
18 execute_curl_http_request(http_request);
19}
删除 Instance
当用户不再使用某个 Instance 时,可将其删除,但需要注意的是,被删除的 Instance 必需是空的,即其中没有表存在,否则会拒绝删除操作。
C++
1void drop_instance() {
2 // 将删除名为ins_demo的instance
3 const std::string instance_name = "ins_demo";
4 // 初始化HttpRequest
5 HttpRequest http_request;
6 http_request.url = "http://bts.bd.baidubce.com";
7 // 方法为DELETE表示删除资源
8 http_request.method = "DELETE";
9 http_request.path = "/v1/instance/" + instance_name;
10 // 获取当前时间戳
11 time_t timestamp = time(NULL);
12 // 注意Http请求中的x-bce-date与生成认证字符串的时间需一致
13 http_request.headers["x-bce-date"] = timestamp_to_utc(timestamp);
14 http_request.headers["Host"] = "bts.bd.baidubce.com";
15 http_request.headers["Authorization"] = gen_authorization(http_request, timestamp);
16
17 execute_curl_http_request(http_request);
18}
百度智能云认证字符串 C++实现
C++
1// UriEncode实现,except_slash参数表示是否编码'/'
2inline std::string uri_encode(const std::string& src, bool except_slash = false) {
3 static const char* hex = "0123456789ABCDEF";
4 std::string dst = "";
5 for (size_t i = 0; i < src.length(); i++) {
6 char c = src[i];
7 if (isalnum(c) || strchr("-_.~", c)) {
8 dst += c;
9 } else if (except_slash && c == '/') {
10 dst += c;
11 } else {
12 dst += '%';
13 dst += hex[(unsigned char)c >> 4];
14 dst += hex[(unsigned char)c & 0xf];
15 }
16 }
17 return dst;
18}
19
20// UriEncodeExceptSlash实现
21inline std::string uri_encode_except_slash(const std::string& str) {
22 return uri_encode(str, true);
23}
24
25// HmacSha256 的实现
26std::string hmac_sha256(const std::string& key, const std::string& message) {
27 unsigned char digest[SHA256_DIGEST_LENGTH];
28 unsigned int digestLength;
29
30 HMAC_CTX ctx;
31 HMAC_CTX_init(&ctx);
32 HMAC_Init_ex(&ctx, key.c_str(), key.length(), EVP_sha256(), NULL);
33 HMAC_Update(&ctx, reinterpret_cast<const unsigned char*>(message.c_str()), message.length());
34 HMAC_Final(&ctx, digest, &digestLength);
35 HMAC_CTX_cleanup(&ctx);
36
37 std::stringstream ss;
38 ss << std::hex << std::setfill('0');
39 for (unsigned int i = 0; i < digestLength; i++) {
40 ss << std::setw(2) << static_cast<unsigned int>(digest[i]);
41 }
42
43 return ss.str();
44}
45
46// 百度智能云认证字符串生成的C++实现
47// 其中有一些加密函数由于有公开库,我们这里直接调用,用户可找相应的公开库(如openssl)
48// 用户可以参考百度智能云生成认证字符串流程来阅读以下实现代码
49std::string gen_authorization(const HttpRequest& request, time_t timestamp) {
50 // 1. 生成CanonicalRequest
51 std::string http_method = request.method;
52 // 1.1 生成CanonicalURI,
53 std::string canonical_uri = uri_encode_except_slash(request.path);
54 // 1.2 计算CanonicalQueryString
55 std::string canonical_query = "";
56 // 使用set结构暂存在后续遍历时可以保证天然字典序遍历,如果使用vector暂存需要配合sort按字典序排序
57 std::set<std::string> encoded_params;
58 // 对params遍历一次对kv做urlencode
59 auto params_it = request.params.begin();
60 for (; params_it != request.params.end(); ++params_it) {
61 if (params_it->first == "authorization" || params_it->first == "Authorization") {
62 continue;
63 }
64 std::string key = uri_encode(params_it->first);
65 std::string value = uri_encode(params_it->second);
66 encoded_params.insert(key + '=' + value); // 兼容value为空字符串的情形
67 }
68 // 对params遍历urlencode后的集合,拼接字符串
69 auto enc_params_it = encoded_params.begin();
70 for (; enc_params_it != encoded_params.end(); ++enc_params_it) {
71 if (enc_params_it != encoded_params.begin()) {
72 canonical_query += '&';
73 }
74 canonical_query += *enc_params_it;
75 }
76 // 1.3 计算CanonicalHeaders
77 std::string canonical_header = "";
78 std::string signed_headers = "";
79 // 使用set结构暂存在后续遍历时可以保证天然字典序遍历,如果使用vector暂存需要配合sort按字典序排序
80 std::set<std::string> encoded_headers;
81 // 对headers遍历一次,对key做转换小写、urlencoded操作,对value做去首尾空格、urlencoded操作
82 auto headers_it = request.headers.begin();
83 for (; headers_it != request.headers.end(); ++headers_it) {
84 // 将key部分转换为全小写
85 std::string key = headers_it->first;
86 for (size_t i = 0; i < key.length(); ++i) {
87 key[i] = ::tolower(key[i]);
88 }
89 // 将value部分去掉首尾的空白符
90 const char* blank_chars = " \n\r\t\v";
91 std::string value = headers_it->second;
92 value.erase(0, value.find_first_not_of(blank_chars));
93 value.erase(value.find_last_not_of(blank_chars) + 1);
94 if (value.empty()) {
95 continue;
96 }
97 std::string encoded_key = uri_encode(key);
98 std::string encoded_value = uri_encode(value);
99 encoded_headers.insert(encoded_key + ':' + encoded_value);
100 if (!signed_headers.empty()) {
101 signed_headers += ";";
102 }
103 signed_headers += encoded_key;
104 }
105 // 对headers遍历urlencode后的集合,拼接字符串
106 auto enc_headers_it = encoded_headers.begin();
107 for (; enc_headers_it != encoded_headers.end(); ++enc_headers_it) {
108 if (enc_headers_it != encoded_headers.begin()) {
109 canonical_header += '\n';
110 }
111 canonical_header += *enc_headers_it;
112 }
113 // 拼接生成CanonicalRequest
114 std::string canonical_request = http_method + '\n'
115 + canonical_uri + '\n'
116 + canonical_query + '\n'
117 + canonical_header;
118 // 2. 生成SigningKey,这里我们直接调用了hmac_sha256函数,用户可以使用任意公开库中的HMAC-SHA256-HEX函数代替
119 // 注意使用hmac_sha256函数时参数的顺序
120 // 在生成鉴权串时的时间戳一定要和发送请求中Header域中的Date/x-bce-date相同
121 // 用户的ak/sk
122 const std::string ak = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
123 const std::string sk = "ssssssssssssssssssssssssssssssss";
124 // 拼接认证字符串前缀 : bce-auth-v1/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}
125 std::string auth_string_prefix = "bce-auth-v1/";
126 auth_string_prefix.append(ak + '/');
127 auth_string_prefix.append(timestamp_to_utc(timestamp));
128 // 认证字符串的超时时间(有效期)为1800秒,用户可以自行设置,时间长意味着效率高,但安全性会降低
129 auth_string_prefix.append("/1800");
130 std::string sign_key = hmac_sha256(sk, auth_string_prefix);
131 // 3. 生成Signature
132 std::string sign = hmac_sha256(sign_key, canonical_request);
133 // 4. 生成认证字符串,即做拼接
134 // 将前缀和Signature拼接得到完整的认证字符串
135 // 与签名结果之间为两个”/”,含义是使用默认签名方式
136 std::string auth = auth_string_prefix + "/" + signed_headers + "/" + sign;
137 return auth;
138}