为什么UriComponentsBuilder忽略空查询参数?

5

我正在尝试构建一个 url UriComponentsBuilder

UriComponentsBuilder.fromUriString(BASE)
                .pathSegment("api")
                .pathSegment("v1")
                .queryParam("param1", userId) //userId in null
                .queryParam("param2",productId) //productId 12345
                .build().toUriString();

我得到的结果如下,正如预期的那样。
"http://localhost/api/v1?param1=&param2=12345"

当这些查询参数中的一个为空时,我不希望该参数键成为URL的一部分。那么当参数为空时,如何动态构建URL呢?我期望的结果类似于:
"http://localhost/api/v1?param2=12345"

这个回答解决了你的问题吗?如何动态删除空的查询参数? - samabcde
1个回答

15

我认为你可能想使用UriComponentsBuilder::queryParamIfPresent这个函数来替换你目前正在使用的函数。

从官方文档可以看出:

如果值不是 Optional::empty,则该函数将添加一个查询参数。如果为空,则不会添加参数。

要将你的 null 转换为 Optional,请使用 Optional::ofNullable

代码示例:

UriComponentsBuilder.fromUriString(BASE)
    .pathSegment("api")
    .pathSegment("v1")
    .queryParamIfPresent("param1", Optional.ofNullable(userId)) // UserId is null
    .queryParamIfPresent("param2", Optional.ofNullable(productId)) // ProductId 12345
    .build()
    .toUriString();

这将导致URI中的查询字符串没有param1,然而因为param2不为空,将把它添加到查询字符串中。
希望这能帮到你。
祝一切顺利!
-T

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接