【问题标题】:RestTemplate and UriComponentsBuilder to access APIRestTemplate 和 UriComponentsBuilder 访问 API
【发布时间】:2021-10-26 10:46:49
【问题描述】:

我正在尝试访问具有表示为 JSON 的查询参数的 API 的内容,我需要使用 RestTemplate 和 UriComponentsBuilder 发送一个 URL

API: http://remote-api/person?filter={"code":"30ABD999"}&page=0&size=1&sort=name

 public Person getPerson(String filter, Optional<Integer> size, 
                         Optional<Integer> page, Optional<String> sort){

        String endpoint= "http://localhost:8081/person"

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(this.endpoint)
                .queryParam("filter",filter);

        page.ifPresent(p -> builder.queryParam("page", p));
        size.ifPresent(s -> builder.queryParam("size", s));
        sort.ifPresent(s -> builder.queryParam("sort", s));

        String url = builder.build().toUriString();

        ResponseEntity<Person> response = 
        this.restTemplate.getForObject(url, null, Person.class);

        return response.getBody();
    }


    

当我提出请求时出现此错误

Raised java.lang.IllegalArgumentException: Not enough variable values available to expand '"code"'

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: java json spring spring-boot resttemplate


    【解决方案1】:

    您不能将null 作为getForObject 中的第二个参数传递。
    试试这样:

    this.restTemplate.getForObject(url, Person.class);
    

    有关如何在 Spring 中使用 HTTP 客户端的更多详细信息可以在我的德语博客中找到:
    https://agile-coding.blogspot.com/2021/01/reactive-webclient.html

    【讨论】:

    • 感谢您的回复,但我遇到了同样的错误
    猜你喜欢
    • 2014-09-03
    • 2018-04-13
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 2022-06-28
    • 1970-01-01
    • 2019-01-26
    相关资源
    最近更新 更多