我正在尝试构建一个urlUriComponentsBuilder
。
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"
当其中一个查询参数为null时,我不希望该参数key成为url的一部分。当参数为空时,如何动态构造URL。我希望是这样的:
"http://localhost/api/v1?param2=12345"
我想你可能想用UriComponentsBuilder::queryParamIfPresent
代替你目前使用的功能。
来自官方文档:
如果查询参数的值不是
Optional::empty
,则增加查询参数。如果为空,则根本不会添加该参数。
用Optional::ofNullable
把你的null
变成Optional
。
代码示例:
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