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

我正在尝试构造一个 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"

最佳答案

我想你可能想使用 UriComponentsBuilder::queryParamIfPresent而不是您当前正在使用的功能。

来自官方文档:

This function will add a query parameter if its value is not Optional::empty. If it's empty, the parameter won't be added at all.

要将您的 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();

这将导致在其查询字符串中没有 param1 的 URI。 但是,param2 将被添加到查询字符串中,因为它不是空的。

希望这对你有帮助。

干杯!

-T

https://stackoverflow.com/questions/69515861/

相关文章:

java - 如何在输出控制台中阻止 Apache Ignite 消息 "Possible too

css - 在 MUI v5 中更改抽屉的颜色

typescript - vue3 vite 别名无法按预期使用 typescript

python - 查找 NetworkX 中所有节点对之间的所有最短路径

python - 如何对齐 __str__ 输出中的列表?

html - 标签内的 div 换行

tensorflow - 获取错误 "Resource exhausted: OOM when al

r - DataFrame 中多列的 Ifelse

python - "Group"行基于一列,然后为现有其他列值的可能组合创建新列

c# - 了解 "await"在异步方法中的用法