SpringBoot之RestTemple介绍

简介

在写项目于中我们经常需要调用远程和HTTP接口,Spring官方提供了RestTemple类,使我们发送HTTP请求更加便捷。

我们学习RestTemple之前我们看看官方文档是怎么描述的。Spring官方文档

Synchronous client to perform HTTP requests, exposing a simple, template method API over underlying HTTP client libraries such as the JDK HttpURLConnection, Apache HttpComponents, and others. RestTemplate offers templates for common scenarios by HTTP method, in addition to the generalized exchange and execute methods that support less frequent cases

RestTemplate是一个同步的HTTP请求客户端,通过在JDK的HttpURLConnection、Apache HttpComponents等底层HTTP客户端库上暴露简单的模板方法API,使得进行HTTP请求变得更加便捷。RestTemplate提供了按HTTP方法处理常见场景,此外,还提供了通用的exchange和execute方法,支持不太常见的使用情景。

环境配置

添加RestTemple的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

编写Spring配置类,注册将Bean注册到容器中

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }

在需要使用RestTemple时注入RestTemple实例

@Autowired
private RestTemplate restTemplate;

基本使用

发送GET请求


要发起GET请求,可以使用getForObject()或getForEntity()方法。getForObject()方法将响应体作为对象返回,而getForEntity()方法返回完整的响应,包括头部信息和状态码。

// 发出 GET 请求并以字符串形式返回
String  response  = restTemplate.getForObject( "url" , String.class); 

// 发出 GET 请求并返回整个响应对象
ResponseEntity<String> response =restTemplate.getForEntity( "url" , String.class);

发送POST 请求


要发出 POST 请求,您可以使用postForObject()或postForEntity()方法。这些方法的工作方式与 GET 方法类似,方法postForObject()将响应正文作为对象返回,方法postForEntity()返回整个响应。

// 发出 POST 请求并以字符串形式返回
String  response  = restTemplate.postForObject( "url" , new Post (), String.class); 

// 发出 POST 请求并返回整个响应对象
ResponseEntity<String> response =restTemplate.postForEntity( "url" , new Post (), String.class);



发送 PUT 和 DELETE 请求


要发出 PUT 和 DELETE 请求,您可以分别使用put()和delete()方法。

// 发出 PUT 请求
restTemplate.put( "url" , new  Post ()); 

// 发出 DELETE 请求
restTemplate.delete( "url" );

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值