2017-08-10 60 views
0

我用彈簧安置模板實現API爲什麼通過PARAM名稱是強制性的RestTemplate春

https://theysaidso.com/api/#qod 

。我的問題是,如果我讓它像下面的網址一樣。但是,如果我從括號中刪除參數名稱,它不會返回錯誤。任何想法?謝謝!

這工作:

QuoteResponse quoteResponse=  
this.restTemplate.getForObject("http://quotes.rest/qod.json?category= 
{param}", QuoteResponse.class, category); 

這並不

QuoteResponse quoteResponse=  
this.restTemplate.getForObject("http://quotes.rest/qod.json?category={}", 
QuoteResponse.class, category); 

我想象,這兩個轉換爲以下(以值傳遞作爲激勵的類別序列

"http://quotes.rest/qod.json?category=inspire" 

更新(添加更多代碼):控制器

@Autowired 
QuoteService quoteService; 

@RequestMapping(value="/ws/quote/daily", produces=MediaType.APPLICATION_JSON_VALUE,method=RequestMethod.GET) 
public ResponseEntity<Quote> getDailyQuote(@RequestParam(required=false) String category){ 
    Quote quote = quoteService.getDaily(category); 
    if(quote==null) 
     return new ResponseEntity<Quote>(HttpStatus.INTERNAL_SERVER_ERROR); 
    return new ResponseEntity<Quote>(quote,HttpStatus.OK); 

} 

QuoteService.getDaily

@Override 
public Quote getDaily(String category){ 
    if(category==null || category.isEmpty()) 
     category=QuoteService.CATEGORY_INSPIRATIONAL; 
    QuoteResponse quoteResponse= 
      this.restTemplate.getForObject("http://quotes.rest/qod.json?category={cat}", 
        QuoteResponse.class, category); 


    return quoteResponse.getContents().getQuotes()[0];  
} 
+0

粘貼控制器代碼幫助我們尋找到這一點。 – Lovababu

+0

@Lovababu加了 – Vikash

+0

因爲你有「required = false」,spring不會強迫你傳遞查詢參數。和category = {any_name},這裏* {any_name} *只是RestTemplate的一個佔位符,它在進行實際的休息調用之前用提供的uriVariable替換此佔位符。 – Lovababu

回答

1
this.restTemplate.getForObject("http://quotes.rest/qod.json?category= 
{param}", QuoteResponse.class, category); 

當你做出這樣的請求,這意味着要傳遞PathVariable成由@PathVariable註釋在控制器的參數handeled控制器。

PathVariable是需要爲了讓你的工作完成,如果控制器有@PathVariable就可以了。

restTemplate.getForObject("http://quotes.rest/qod.json?category={}", 
QuoteResponse.class, category); 

當你做出這樣的請求,你是不是送你的要求其在這裏需要任何PathVariable,所以不工作,並拋出MissingPathVariableException

+0

@謝謝!我假設你的意思是RequestParameter不是PathVariable,因爲我理解的路徑變量會像/quotes.rest/qod.json/{cat}和//quotes.rest/qod.json?category={cat}用於請求參數。 但是對於這個問題,RequestParam應該有一個名字,對吧?而它適用於任何傳遞的名稱,即 this.restTemplate.getForObject(「http://quotes.rest/qod.json?category= {param}」,QuoteResponse.class,category).. works ..和。這也適用。 this.restTemplate.getForObject(「http://quotes.rest/qod.json?category= {param12345}」,QuoteResponse.class,category) – Vikash