首页 > 解决方案 > 集合的 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 的建议使用。

标签: javaspringuriresttemplate

解决方案


您不能将对象作为请求参数传递。请求参数是字符串到字符串的多值映射。如果您想将 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

推荐阅读