提示信息

RestTemplate 用例

蕾溪 已关注

RestTemplate 是 Spring 框架中用于发送 HTTP 请求的一个类。以下是一个发送 GET 和 POST 请求的例子:

  1. import org.springframework.http.HttpEntity;
  2. import org.springframework.http.HttpHeaders;
  3. import org.springframework.http.MediaType;
  4. import org.springframework.web.client.RestTemplate;
  5. public class Application {
  6. public static void main(String[] args) {
  7. RestTemplate restTemplate = new RestTemplate();
  8. // 发送 GET 请求
  9. String resultGet = restTemplate.getForObject("http://example.com", String.class);
  10. System.out.println(resultGet);
  11. // 发送 POST 请求
  12. String requestJson = "{\"id\":1,\"name\":\"John\"}";
  13. HttpHeaders headers = new HttpHeaders();
  14. headers.setContentType(MediaType.APPLICATION_JSON);
  15. HttpEntity<String> entity = new HttpEntity<>(requestJson,headers);
  16. String resultPost = restTemplate.postForObject("http://example.com", entity, String.class);
  17. System.out.println(resultPost);
  18. }
  19. }

在这个示例中,我们首先创建了一个 RestTemplate 实例。

然后,使用 getForObject 方法发送一个 GET 请求到 "http://example.com",并将响应体作为字符串返回。

接着,我们创建一个 JSON 字符串 requestJson,并设置 HTTP 头以指明内容类型为 JSON。然后,使用 postForObject 方法发送一个 POST 请求到 "http://example.com",并将 requestJson 作为请求体。服务器的响应又被转化为一个字符串并打印出来。

请注意,从 Spring 5 开始,官方建议使用 WebClient 替代 RestTemplate,因为 WebClient 提供了更多的功能并且支持非阻塞 IO。

蕾溪 关注 已关注

最近一次登录:2023-09-26 22:05:21   

暂时还没有签名,请关注我或评论我的文章
×
分享到朋友圈