Spring Boot 使用RestTemplate调用外部接口
(Spring Boot 已内置,无需额外添加)
·
步骤:
-
添加依赖(Spring Boot 已内置,无需额外添加)
-
创建 RestTemplate Bean
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } -
调用外部接口
@Service
public class ApiService {
@Autowired
private RestTemplate restTemplate;
// GET 请求示例
public ResponseEntity<String> getData() {
String url = "https://api.example.com/data";
return restTemplate.getForEntity(url, String.class);
}
// POST 请求示例(带JSON参数)
public ResponseEntity<String> postData(Object request) {
String url = "https://api.example.com/create";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> entity = new HttpEntity<>(request, headers);
return restTemplate.postForEntity(url, entity, String.class);
}
}
更多推荐
所有评论(0)