如何使用RESTinio便捷提取REST API请求中的查询参数?
解决方案:解析RESTinio请求中的嵌套参数
你的请求URL格式比较特殊,query部分包含额外的GetInformationMethod?前缀,直接用restinio::parse_query解析整个strUrl会把GetInformationMethod当作无效参数。要拿到Type和OtherParam的键值对,需要先处理query字符串,再调用RESTinio的解析函数:
步骤1:提取有效参数部分
先从strUrl中截取出Type=2304&OtherParam=1234这部分核心参数内容:
std::string strUrl(query.data(), query.length()); // 定位第二个问号位置,跳过前缀`GetInformationMethod?` size_t second_question_mark = strUrl.find('?', strUrl.find('?') + 1); if (second_question_mark != std::string::npos) { std::string params_str = strUrl.substr(second_question_mark + 1);
步骤2:用RESTinio解析成键值对集合
调用restinio::parse_query处理截取后的参数字符串,直接得到键值对集合:
const restinio::query_string_params_t qp = restinio::parse_query(params_str);
步骤3:访问目标参数
通过键名直接获取对应的值,也可以结合类型转换得到数值类型(参考你之前的问题):
// 获取字符串形式的参数值 std::string type_str = qp["Type"]; std::string other_param_str = qp["OtherParam"]; // 转换为数值类型 long type = std::stol(qp.get_value_or("Type", "0")); int other_param = std::stoi(qp.get_value_or("OtherParam", "0")); }
处理后即可得到你需要的键值对:
Type 2304 OtherParam 1234
内容的提问来源于stack exchange,提问作者Dominique
相关产品推荐
相关产品推荐

