【发布时间】:2020-12-22 05:10:40
【问题描述】:
我正在调用支持一堆可选查询参数的下游。
同样,我只是有时想添加这些查询参数,但这样做有点烦人
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());
}
}
但肯定有更好的方法吗?
【问题讨论】:
-
在我看来使用地图很好。不要以为你会找到任何 API 让这看起来更干净。
标签: java jersey jersey-client query-parameters