在SpringMVC中使用RestTemplate發(fā)送HTTP請求可以通過以下步驟實現(xiàn):
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Autowired
private RestTemplate restTemplate;
String url = "http://example.com/api/resource";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
String responseBody = response.getBody();
// 處理返回的數(shù)據(jù)
} else {
// 處理錯誤
}
以上示例使用RestTemplate發(fā)送GET請求,并獲取返回的數(shù)據(jù)。RestTemplate還提供了其他方法用于發(fā)送POST、PUT、DELETE等HTTP請求。根據(jù)具體的需求,選擇合適的方法發(fā)送HTTP請求。