import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity("", headers);
ResponseEntity responseEntity = restTemplate.exchange("https://api.example.com/users", HttpMethod.GET, entity, String.class);
if (responseEntity.getStatusCode().is2xxSuccessful()) {
String response = responseEntity.getBody();
System.out.println(response);
} else {
System.out.println("HTTP Request failed with status code: " + responseEntity.getStatusCode());
}
}
} SpringBoot中使用RestTemplate类可以方便地实现对各种HTTP请求的调用和处理。通过设置请求的URL、请求方法、请求头和请求体,可以发送不同类型的HTTP请求,并获取服务器返回的响应数据。
在以上示例中,我们创建了一个RestTemplate实例,并设置了请求头的content-type为application/json。然后,根据API文档中提供的URL,发送GET请求。如果响应的状态码是2xx成功的,则打印响应的内容;否则,打印HTTP请求失败的状态码。
通过使用RestTemplate,我们可以轻松实现与远程服务的交互,例如获取数据、发送数据和执行其他HTTP操作。