java - 集合的 RestTemplate URI 模板语法?

标签 java spring uri resttemplate

我有一个带有方法的 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:无法将类型“java.lang.String”的值转换为所需类型“java.util.List”;嵌套异常为 java.lang.NumberFormatException:对于输入字符串:“[573]”);正确的是 search?network-ids[]=77371&usages[]=MESSAGE_DELIVERY

很可能 URI 模板是错误的。应该如何与 Java 集合一起使用?

更新:我创建了一个不带括号的新 API 端点,并按照 @vatsal 的建议使用了 UriComponentsBuilder

最佳答案

要轻松操作 URL/路径/参数等,可以使用 Spring 的 UriComponentsBuilder 类。手动连接字符串更简洁,并且它会为您处理 URL 编码:

使用 RestTemplate 执行此操作的简单代码如下:

HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);

String url = "http://castor-v2/providers/usable/search";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
            .queryParam("country-id", countryId)
            .queryParam("network-ids[]", networkId)
            .queryParam("usages[]", Usage.MESSAGE_DELIVERY);

HttpEntity<?> entity = new HttpEntity<>(httpHeaders);

HttpEntity<String> response = restTemplate.exchange(
            builder.toUriString(),
            HttpMethod.GET,
            entity,
            String.class);

这应该可以解决您的疑问。另外,请确保将“Usage”作为字符串传递。如果您仍然想继续使用Usage作为对象,那么您可以使用RequestBody代替RequestParam并将其作为Body传递给POST调用。

关于java - 集合的 RestTemplate URI 模板语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56750496/

相关文章:

java - SpringMVC : how to get the value of @RequestMapping in the function

Spring Data REST - 发布具有关系的新实体

character-encoding - 数据 URI 默认字符集

url - URI 查询中什么是有效的,什么是无效的?

java - 安卓分享按钮

java - JPA 不想在 Spring Boot 中创建表

java - 更改 ENTER 键功能

Java Util Logging 重定向到 Log4j2 不适用于 Spring Boot 应用程序

java - Android - 计算服务器目录中的文件数

java - 查询内存中的集合