使用 Spring RestTemplate 访问 Rest 服务

本文介绍了如何使用Spring的RestTemplate类来访问REST服务。RestTemplate是Spring 3.0引入的,它简化了HTTP请求的发起和响应处理。文章详细讲解了RestTemplate的GET、POST、PUT、DELETE以及其他HTTP方法的使用,并提供了相关方法的重载选项。同时,提到了通用请求方法execute()和exchange(),并指出execute()操作复杂,推荐使用exchange()。最后,补充说明测试代码可在作者的GitHub仓库中获取。
摘要由CSDN通过智能技术生成

RestTemplate简介

Spring's central class for synchronous client-side HTTP access.
It simplifies communication with HTTP servers, and enforces RESTful principles.
It handles HTTP connections, leaving application code to provide URLs(with possible template variables) and extract results.

  上面这段是RestTemplate类中的简单介绍,RestTemplate是Spring3.0后开始提供的用于访问 Rest 服务的轻量级客户端,相较于传统的HttpURLConnection、Apache HttpClient、OkHttp等框架,RestTemplate大大简化了发起HTTP请求以及处理响应的过程。本文关注RestTemplate是如何使用的,暂不涉及内部的实现原理。

  RestTemplate支持多种的请求方式,具体参考下表:

HTTP method RestTemplate methods
GET getForObject、getForEntity
POST postForObject、postForEntity、postForLocation
PUT put
DELETE delete
HEAD headForHeaders
OPTIONS optionsForAllow
PATCH patchForObject
any exchange、execute

引入RestTemplate

  • 方式一,使用无参构造器直接new一个对象
    private RestTemplate restTemplate = new RestTemplate();
  • 方式二,先注册成Spring的Bean对象,之后使用的时候直接注入
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Autowired
    private RestTemplate restTemplate;

测试准备

  新建User对象,用于下面不同请求方式的测试。

@Data
public class User {

    /**
     * id
     */
    private Long id;

    /**
     * 用户名
     */
    private String username;

    /**
     * 年龄
     */
    private Integer age;
    
}

GET请求

  GET请求对应两个方法,getForObject()和getForEntity(),每个方法又对应有具体的三个重载方法。这两者的区别在于getForObject()返回的是一个简单的对象,而getForEntity()响应的数据中,还额外包含有与HTTP相关的信息,如响应码、响应头等。

RestTemplate-getForObject

    /**
     * GET资源 (发送一个HTTP GET请求,返回的请求体将映射为一个对象)
     * <p>
     * 1. 执行根据URL检索资源的GET请求
     * 2. 根据responseType参数匹配为一定的类型
     * 3. getForObject()只返回所请求类型的对象信息
     */
    @Test
    public void getForObject() {
        long id = 0;
        //URL中的{id}占位符最终将会用方法的id参数来填充
        String url = "http://localhost:9000/user/{id}";


        //重载1:最后一个参数是大小可变的参数列表ÿ
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值