我用彈簧安置模板實現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];
}
粘貼控制器代碼幫助我們尋找到這一點。 – Lovababu
@Lovababu加了 – Vikash
因爲你有「required = false」,spring不會強迫你傳遞查詢參數。和category = {any_name},這裏* {any_name} *只是RestTemplate的一個佔位符,它在進行實際的休息調用之前用提供的uriVariable替換此佔位符。 – Lovababu