如何解决javax.ws.rs.client.WebTarget可选queryparam
同样,我有时只想添加那些queryparams,但是这样做会很烦人
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
}
,如果有多个可选的queryparams,则会导致组合爆炸。
总是添加queryparams,但是在不需要时将值设置为空字符串或null也不起作用-添加具有null值的queryparam会导致NPE,而发送空字符串会导致添加查询参数,但没有价值。
我想出了解决方法
public Map<Subject,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 ...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。