Spring Boot API Call with RestTemplate

In Spring Boot, the typical way to call an API is using the RestTemplate class. RestTemplate is a template class provided by Spring for calling RESTful HTTP services, which encapsulates the operations of HTTP requests, making it easy to send requests and handle responses.

Here is a simple example demonstrating how to use RestTemplate to call an API.

RestTemplate restTemplate = new RestTemplate();
String url = "http://api.example.com/data";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

if(response.getStatusCode() == HttpStatus.OK) {
    String responseBody = response.getBody();
    // 处理响应数据
} else {
    System.out.println("接口调用失败,状态码:" + response.getStatusCode());
}

In the example above, we first create a RestTemplate instance and then use the getForEntity method to send a GET request to a specific URL, specifying the type of data to be returned as String. Next, we check the response status code of the API, and if the code is 200 (HttpStatus.OK), we have successfully retrieved the response data and can proceed with handling it.

In addition to GET requests, RestTemplate offers other methods for sending different types of HTTP requests such as POST, PUT, DELETE, etc. Developers can choose the appropriate method based on their actual needs to call the interface.

bannerAds