java - 集合的 RestTemplate URI 模板语法?
问题描述
我有一个带有方法的 Spring Boot 2 服务
@RequestMapping(path = "/usable/search")
public List<Provider> findUsable(
@RequestParam(name = "country-id", required = false) Integer countryId,
@RequestParam(name = "network-ids[]", required = false) List<Integer> networkIds,
@RequestParam(name = "usages[]") Set<Usage> usages)
我想从另一个 Spring Boot 服务调用该服务。为此我做
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
val response =
restTemplate.exchange(
"http://castor-v2/providers/usable/search?network-ids[]={0}&usages[]={1}",
HttpMethod.GET,
new HttpEntity<Long>(httpHeaders),
new ParameterizedTypeReference<List<Provider>>() {},
Collections.singletonList(networkId),
Collections.singleton(Usage.MESSAGE_DELIVERY));
这会生成一个search?network-ids[]=[428]&usages[]=[MESSAGE_DELIVERY]
错误的 http 请求(服务器用 轰炸org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.List'; nested exception is java.lang.NumberFormatException: For input string: "[573]"
);正确的是search?network-ids[]=77371&usages[]=MESSAGE_DELIVERY
。
URI 模板很可能是错误的。它应该如何与 Java 集合一起使用?
更新:我创建了一个不带括号的新 api 端点,并UriComponentsBuilder
按照@vatsal 的建议使用。
解决方案
您不能将对象作为请求参数传递。请求参数是字符串到字符串的多值映射。如果您想将 Usage 作为 String 传递,您可以创建这样的方法
@RequestMapping(path = "/usable/search")
public List<Provider> findUsable(
@RequestParam(name = "country-id", required = false) Integer countryId,
@RequestParam(name = "networkIds", required = false) List<Integer> networkIds,
@RequestParam(name = "usages") Set<String> usages)
调用此服务
http://castor-v2/providers/usable/search?networkIds=0&networkIds=1&usages=usages1&usages=usages2
推荐阅读
- sql - SQL 将行转置为列
- web-services - 在 Jmeter 中处理soap+msbin1 内容类型
- angular6 - 如何在Angular6中的我的角度模板上显示来自byte64字符串的PDF
- pentaho - 五角连接变量
- java - Google 登录无法在已发布的应用上运行
- javascript - 带有错误消息的jQuery多个下拉类过滤器
- grafana - visualization graph Grafana
- sql-server - 顺序列名
- ios - 在 iOS 的自定义框架中嵌入 coredata
- java - 对于 MongoClient 类型,方法 getDatabase(String) 未定义