java - javax.ws.rs.client.WebTarget 可选查询参数
问题描述
我正在调用支持一堆可选查询参数的下游。
同样,我有时只是想添加那些查询参数,但是这样做有点烦人
public Map<Subject, Role> getGrantsForResource(
final String propertyId,
final boolean filterByRole
) {
final WebTarget resource;
if (filterByRole) {
resource = ramClient
.path("/v1/resource/{resource}/grants")
.resolveTemplate("resource", "resource.property." + propertyId)
.queryParam("role", "role.23"); //add queryparam
} else {
resource = ramClient
.path("/v1/resource/{resource}/grants")
.resolveTemplate("resource", "resource.property." + propertyId);
//don't add queryparam
}
并且在多个可选查询参数的情况下会导致组合爆炸。
始终添加查询参数,但在不需要时将值设为空字符串或 null 也不起作用 - 添加值为 null 的查询参数会导致 NPE,发送空字符串会导致添加查询参数,但使用没有价值。
我想出了这个解决方法
public Map<Subject, Role> getGrantsForResource(
final String propertyId,
final Map<String, String> queryParams
) {
WebTarget resource = ramClient
.path("/v1/resource/{resource}/grants")
.resolveTemplate("resource", "resource.property." + propertyId);
for (Map.Entry<String, String> e : queryParams.entrySet()) {
if (e.getValue() == null) {
//don't add queryparam
} else {
resource = resource.queryParam(e.getKey(), e.getValue());
}
}
但肯定有更好的方法吗?
解决方案
构建 WebTarget 时可以跳过空值。
public Map<Subject, Role> getGrantsForResource(
final String propertyId,
final Map<String, String> queryParams) {
WebTarget resource = ramClient
.path("/v1/resource/{resource}/grants")
.resolveTemplate("resource", "resource.property." + propertyId);
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
if (entry.getValue() != null) {
webTarget = webTarget.queryParam(entry.getKey(), entry.getValue());
}
}
// use webTarget ...
}
推荐阅读
- android - IKEv2 如何在没有原始套接字的 Android 上工作
- mongodb - 在 mongodb 聚合中的数组内查找嵌套对象字段
- django - 为 Django+React 项目设置部署,每个项目都使用 Nginx 在不同的端口上运行
- mysql - MySQL-将单个转义字符插入 MySQL JSON 字段
- python - 由 PyDub AudioSegment.split_on_silence() 产生的 .WAV 音频在使用 wave.open 读取时没有 RIFF ID
- reactjs - React hook useEffect 无法读取使用 firebase 的 firestore 实时数据更新的新 useState 值
- javascript - 在呈现页面后尝试从 JavaScript 函数访问模型数据 NodeJS EJS
- websphere - IBM ODM 相关 XOM 类
- c# - 如何在 C# net core 中从数据库中获取数据
- python - Python:用多个值替换单个字符