【发布时间】:2018-10-11 06:18:23
【问题描述】:
嘿,我有这个包含多个查询参数的 url - 它用于搜索。这是一个讨厌的链接
https://someurl/customers?customer-id={customer-id}&type={type}&something={something}
我希望只替换其中两个参数
Map<String, String> params = new HashMap<>();
params.put("customer-id", customerId);
params.put("something", something)
UriComponents customerUrl = UriComponentsBuilder
.fromHttpUrl(specialURL)
.buildAndExpand(params).encode();
但这会抛出。
java.lang.IllegalArgumentException: Map has no value for 'type'
at org.springframework.web.util.UriComponents$MapTemplateVariables.getValue(UriComponents.java:346) ~[spring-web-5.0.8.RELEASE.jar:5.0.8.RELEASE]
这里最好的解决方法是什么,假设我有大约 7 个参数,用空字符串替换它们或将字符串切成两半似乎相当 hacky。
【问题讨论】:
-
它的内部实现要求所有的键必须存在于参数中,否则你会得到这个异常。
-
您可能需要解析特殊 URL 的查询字符串并将其放入地图中。现在你知道了没有 query 的 url。你知道你想发送什么,所以你可以在这里使用两种方法。 1) 仅附加要编码的 URL 中存在的参数。 2)总是实例化完整的地图(所有非必填字段为空白/空/空(任何工作)并保留一些值)。然后你可以在 uri 组件构建器中传递该映射。
-
想要删除所有查询参数的人可以这样做:
builder.replaceQuery("")
标签: java spring http spring-boot resttemplate