【发布时间】:2018-01-18 12:19:23
【问题描述】:
我实现了 api
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 添加
-
因为你有“required=false”,spring 不会强迫你传递查询参数。和 category={any_name},这里 {any_name} 只是 RestTemplate 的占位符,它在进行实际的 rest 调用之前用提供的 uriVariable 替换这个占位符。
标签: java spring rest spring-boot resttemplate