RestTemplate 用例
RestTemplate
是 Spring 框架中用于发送 HTTP 请求的一个类。以下是一个发送 GET 和 POST 请求的例子:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
public class Application {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
// 发送 GET 请求
String resultGet = restTemplate.getForObject("http://example.com", String.class);
System.out.println(resultGet);
// 发送 POST 请求
String requestJson = "{\"id\":1,\"name\":\"John\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(requestJson,headers);
String resultPost = restTemplate.postForObject("http://example.com", entity, String.class);
System.out.println(resultPost);
}
}
在这个示例中,我们首先创建了一个 RestTemplate
实例。
然后,使用 getForObject
方法发送一个 GET 请求到 "http://example.com",并将响应体作为字符串返回。
接着,我们创建一个 JSON 字符串 requestJson
,并设置 HTTP 头以指明内容类型为 JSON。然后,使用 postForObject
方法发送一个 POST 请求到 "http://example.com",并将 requestJson
作为请求体。服务器的响应又被转化为一个字符串并打印出来。
请注意,从 Spring 5 开始,官方建议使用 WebClient
替代 RestTemplate
,因为 WebClient
提供了更多的功能并且支持非阻塞 IO。