需求:如何在程序中调用外部API接口获取程序所需的对象
解决方法:使用RestTemplate.exchange()方法
代码如下:
@PostMapping("/test")
@ResponseBody
public String test(@RequestParam Map<String, Object> params){
RestTemplate restTemplate = new RestTemplate();
//入参及头文件
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type","application/json");
HttpEntity httpEntity = new HttpEntity(params, headers);
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//HttpMethod.Get 为get请求 , httpEntity为入参 没有则填null
return restTemplate.exchange("http://localhost:xxxx/xx/week/list", HttpMethod.POST, httpEntity, String.class).getBody();
}