You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Boost.URL对查询参数中的逗号进行百分编码

问题描述

简介

我的程序里有一个Google Places API客户端,使用Boost.URL库构建URL,代码如下:

#include <iostream>
#include <boost/url/src.hpp>
#include <boost/url/encode.hpp>
#include <boost/json/src.hpp>

...

boost::urls::url endpoint("https://maps.googleapis.com/maps/api/place/autocomplete/json");
auto params = endpoint.params();
params.append({"key", "PLACE_API_KEY" });
params.append({"input", "Tower" });
params.append({"radius", "500" });

auto location = std::make_pair(51.507351, -0.127758);
std::string locationString = std::to_string(location.first) + "," + std::to_string(location.second);
params.append({"location", locationString});

std::cout << endpoint.encoded_target().substr() << '\n';

问题

根据URL RFC规范,逗号(,)属于保留字符,因此Boost.URL不会对其进行编码。

上述代码的输出为:

/maps/api/place/autocomplete/json?key=PLACE_API_KEY&input=Tower&radius=500&location=51.507351,-0.127758

若手动将locationString中的,替换为%2C,输出会变为:

/maps/api/place/autocomplete/json?key=PLACE_API_KEY&input=Tower&radius=500&location=51.507351%252C-0.127758

这是因为%被编码为%25,导致结果不符合预期。

疑问

是否可以通过Boost.URL API对查询参数值中的,进行百分编码?


解决方案

当然可以,Boost.URL提供了精细的编码控制能力,以下两种方法可实现需求:

1. 手动编码后添加已编码参数

使用params_encoded()接口传入预编码的参数值,并标记为已编码状态,避免Boost.URL二次编码:

// 先对location字符串做基础查询参数编码
std::string encodedLoc = boost::urls::encode_query_arg(locationString, boost::urls::encode_opts().set_space_to_plus(false));
// 手动将逗号替换为%2C(默认编码规则不处理逗号)
size_t pos = 0;
while ((pos = encodedLoc.find(',', pos)) != std::string::npos) {
    encodedLoc.replace(pos, 1, "%2C");
    pos += 3;
}
// 添加已编码的参数
endpoint.params_encoded().append(boost::urls::param_encoded("location", encodedLoc));

2. 自定义编码规则

通过encode_opts修改保留字符集合,强制让逗号被编码:

// 创建自定义编码选项,移除逗号的保留字符标记
boost::urls::encode_opts opts;
opts.reserved_chars.remove(',');

// 用自定义规则编码location字符串
std::string encodedValue = boost::urls::encode_query_arg(locationString, opts);

// 添加编码后的参数
params.append({"location", encodedValue});

注意事项

  • 第一种方式适合仅需修改单个参数编码的场景,更灵活;
  • 第二种方式会影响所有使用该编码选项的参数,若仅需处理特定参数的逗号,优先选第一种;
  • 原代码中location.secod是拼写错误,需改为location.second才能正常编译。

内容的提问来源于stack exchange,提问作者CAMOBAP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:17:49