Using RestTemplate in Spring. Exception- Not enough variables available to expand

前端 未结 6 1137
走了就别回头了
走了就别回头了 2020-11-29 05:29

I am trying to access the contents of an API and I need to send a URL using RestTemplate.

String url1 = \"http://api.example.com/Search?key=52ddafbe3ee659bad         


        
6条回答
  •  情歌与酒
    2020-11-29 06:11

    The root cause is that RestTemplate considers curly braces {...} in the given URL as a placeholder for URI variables and tries to replace them based on their name. For example

    {pageSize}
    

    would try to get a URI variable called pageSize. These URI variables are specified with some of the other overloaded getForObject methods. You haven't provided any, but your URL expects one, so the method throws an exception.

    One solution is to make a String object containing the value

    String sort = "{\"price\":\"desc\"}";
    

    and provide a real URI variable in your URL

    String url1 = "http://api.example.com/Search?key=52ddafbe3ee659bad97fcce7c53592916a6bfd73&term=&limit=100&sort={sort}";
    

    You would call your getForObject() like so

    OutputPage page = restTemplate.getForObject(url1, OutputPage.class, sort);
    

    I strongly suggest you do not send any JSON in a request parameter of a GET request but rather send it in the body of a POST request.

提交回复
热议问题