【问题标题】:How to use RestTemplate with non String Query Params in Spring Boot?如何在 Spring Boot 中使用带有非字符串查询参数的 RestTemplate?
【发布时间】:2021-04-22 09:12:51
【问题描述】:

我在 Spring Boot 项目中使用 RestTemplate,我有 4 个查询参数,其中 2 个是字符串,一个是 BigDecimal,一个是布尔值:字符串名称、字符串通道、BigDecimal 代码、布尔 isCreated。我想问你如何发送这个非字符串查询参数,因为我看到 getQueryParams() 需要一个 Map。

我正在使用这种实现方式:

    UriComponents uriComponents = UriComponentsBuilder
            .fromHttpUrl(basePath)
            .path(apiPath)
            .getQueryParams(map)
            .encode(); 

我们将不胜感激任何反馈。谢谢!

【问题讨论】:

    标签: java spring-boot rest resttemplate query-parameters


    【解决方案1】:

    对于BigDecimal 和Boollean,您可以尝试使用toString() 和valueOf() 方法。

    public String createUriString(){
        String basePath="http://example.com";
        String apiPath="api";
        String name="example_name";
        String channel="example_channel";
        BigDecimal code = BigDecimal.valueOf(100500);
        boolean isCreated= true;
        MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
        params.set("name",name);
        params.set("channel",channel);
        params.set("code",code.toString());
        params.set("isCreated",String.valueOf(isCreated));
        UriComponents uriComponents = UriComponentsBuilder
            .fromHttpUrl(basePath)
            .path(apiPath)
            .queryParams(params)
                .build();
        return uriComponents.toUriString();
    }
    

    http://example.com/apiname=example_name&channel=example_channel&code=100500&isCreated=true

    您还可以使用 QueryParam 方法。这更容易。

    public String createUriString(){
        String basePath="http://example.com";
        String apiPath="api";
        String name="example_name";
        String channel="example_channel";
        BigDecimal code = BigDecimal.valueOf(100500);
        boolean isCreated= true;
        UriComponents uriComponents = UriComponentsBuilder
                .fromHttpUrl(basePath)
                .path(apiPath)
                .queryParam("name",name)
                .queryParam("channel", channel)
                .queryParam("code", code)
                .queryParam("isCreated", isCreated)
                .build();
        return uriComponents.toUriString();
    }
    

    这段代码的结果与前面的例子类似。

    附:我找不到 getQueryParams(map) 方法。我们可能有不同版本的 Spring Boot。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      相关资源
      最近更新 更多