我正在尝试构造一个 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=¶m2=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
关于java - 为什么 UriComponentsBuilder 忽略空查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69515861/