首页 > 解决方案 > 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());
        }
    }

但肯定有更好的方法吗?

标签: javajerseyjersey-clientquery-parameters

解决方案


构建 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 ...
}

推荐阅读