RestTemplate使用

什么是RestTemplate ?

RestTemplate是Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。

如何使用

编写配置类,注入到Spring容器

```
package com.itdfq.resttemplate.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @Author GocChin
 * @Date 2021/7/20 10:51
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Description:
 */
@Configuration
public class ResttemplateConfig {
    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

```

RestTemplate常用请求方法

用于GET请求
  • getForObject
    参数
    源码:

       @Nullable
        <T> T getForObject(String var1, Class<T> var2, Object... var3) throws RestClientException;
    
        @Nullable
        <T> T getForObject(String var1, Class<T> var2, Map<String, ?> var3) throws RestClientException;
    
        @Nullable
        <T> T getForObject(URI var1, Class<T> var2) throws RestClientException;
    
  • getForEntity
    getForEntity
    源码:

        <T> ResponseEntity<T> getForEntity(String var1, Class<T> var2, Object... var3) throws RestClientException;
    
        <T> ResponseEntity<T> getForEntity(String var1, Class<T> var2, Map<String, ?> var3) throws RestClientException;
    
        <T> ResponseEntity<T> getForEntity(URI var1, Class<T> var2) throws RestClientException;
    
用于POST请求
  • postForObject
    postForObject
    源码:

        @Nullable
        <T> T postForObject(String var1, @Nullable Object var2, Class<T> var3, Object... var4) throws RestClientException;
    
        @Nullable
        <T> T postForObject(String var1, @Nullable Object var2, Class<T> var3, Map<String, ?> var4) throws RestClientException;
    
        @Nullable
        <T> T postForObject(URI var1, @Nullable Object var2, Class<T> var3) throws RestClientException;
    
  • postForEntity
    postForEntity
    源码:

    
        <T> ResponseEntity<T> postForEntity(String var1, @Nullable Object var2, Class<T> var3, Object... var4) throws RestClientException;
    
        <T> ResponseEntity<T> postForEntity(String var1, @Nullable Object var2, Class<T> var3, Map<String, ?> var4) throws RestClientException;
    
        <T> ResponseEntity<T> postForEntity(URI var1, @Nullable Object var2, Class<T> var3) throws RestClientException;
    
兼容多种请求方式的exchange
  • 支持的请求类型有:
        GET,
        HEAD,
        POST,
        PUT,
        PATCH,
        DELETE,
        OPTIONS,
        TRACE;
    
    exchange

例子

创建实体类
package com.itdfq.resttemplate.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;

/**
 * @Author GocChin
 * @Date 2021/7/20 10:54
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Description:
 */
public class HouseInfo implements Serializable {

    private static final long serialVersionUID = 7499502427245128735L;

    private Long l;
    private String city;
    private String street;
    private String address;

    public HouseInfo() {

    }


    public HouseInfo(Long l, String city, String street, String address) {
        this.l = l;
        this.city = city;
        this.street = street;
        this.address = address;
    }

    public static long getSerialVersionUID() {
        return serialVersionUID;
    }

    public Long getL() {
        return l;
    }

    public void setL(Long l) {
        this.l = l;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "HouseInfo{" +
                "l=" + l +
                ", city='" + city + '\'' +
                ", street='" + street + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

编写请求接口
package com.itdfq.resttemplate.controller;

import com.itdfq.resttemplate.entity.HouseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author GocChin
 * @Date 2021/7/20 10:52
 * @Blog: itdfq.com
 * @QQ: 909256107
 * @Description: 测试Controller
 */
@RestController
@Slf4j
public class HouseController {
    @GetMapping("/house/data")
    public HouseInfo getData(@RequestParam("name") String name) {
        return new HouseInfo(1L, "上海", "虹口", "东体小区");
    }

    @GetMapping("/house/data/{name}")
    public String getData2(@PathVariable("name") String name) {
        return name;
    }

    @RequestMapping(value = "/house/save", method = RequestMethod.POST)
    public HouseInfo getData3(@RequestBody HouseInfo houseInfo) {
        log.info("执行了post请求方法");
        return houseInfo;
    }

    @RequestMapping(value = "/house/save", method = RequestMethod.POST, headers = {"token=123456"})
    public HouseInfo getData4(@RequestBody HouseInfo houseInfo) {
        log.info("执行了post 带heads的方法");
        houseInfo.setCity("海南");
        return houseInfo;
    }
}

测试
  • Get请求测试

    /**
         * 发送Get请求,传递参数
         * @param name
         * @return
         */
        @GetMapping("/test1/data")
        public String test1(@RequestParam("name") String name) {
            //使用getForObject
            String forObject = restTemplate.getForObject("http://localhost:8081/house/data?name="+name, String.class);
            System.out.println(forObject);
            //getForEntity
            ResponseEntity<HouseInfo> forEntity = restTemplate.getForEntity("http://localhost:8081/house/data?name=123", HouseInfo.class);
            System.out.println(forEntity);
            System.out.println(forEntity.getStatusCodeValue());
            return forObject;
        }
    

    结果
    浏览器
    控制台:
    控制台
    注意
    当请求返回值用实体类接受的话,实体类中需要加上toString方法,否则请求的数据无法转入json
    get请求无法加入请求头,可以自定义拦截器加入请求头,或者使用exchange方法,加入请求头

  • Post请求

    • 不带请求头

      	/**
           * 发送post请求 不带请求头的方法
           *
           */
          @GetMapping("/test3/save")
          public void test3(){
      
              HouseInfo houseInfo2 = new HouseInfo(2l, "杭州", "余杭", "桃花港");
              HouseInfo houseInfo1 = restTemplate.postForObject("http://localhost:8081/house/save",houseInfo2 , HouseInfo.class);
              System.out.println(houseInfo1);
          }
      

      结果
      结果

    • 带请求头的post请求

      
          /**
           * 带请求头的 post方法
           * restTemplate.postForEntity():返回的信息比较全面 包含请求body headers 状态等等
           */
          @GetMapping("/test4/save")
          public void test4(){
      
              HouseInfo houseInfo2 = new HouseInfo(2l, "杭州", "余杭", "桃花港");
              //设置header信息
              HttpHeaders requestHeaders = new HttpHeaders();
              requestHeaders.setContentType(MediaType.APPLICATION_JSON);
              requestHeaders.add("token","123456");
              //封装信息
              HttpEntity requestEntity =new HttpEntity(houseInfo2,requestHeaders);
              HouseInfo houseInfo1 = restTemplate.postForObject("http://localhost:8081/house/save",requestEntity , HouseInfo.class);
              System.out.println(houseInfo1);
          }
      

      结果:
      执行结果

  • exchange请求

    /**
     * exchange 可以请求
     *     GET,
     *     HEAD,
     *     POST,
     *     PUT,
     *     PATCH,
     *     DELETE,
     *     OPTIONS,
     *     TRACE;
     *     使用exchange 需要制定请求的方式,以及请求参数
     */
    @GetMapping("/test5/save")
    public void test5(){
        HouseInfo houseInfo2 = new HouseInfo(2l, "杭州", "余杭", "桃花港");
        //设置header信息
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        requestHeaders.add("token","123456");
        //封装信息
        HttpEntity requestEntity =new HttpEntity(houseInfo2,requestHeaders);
        ResponseEntity<HouseInfo> exchange = restTemplate.exchange("http://localhost:8081/house/save", HttpMethod.POST, requestEntity, HouseInfo.class);
        System.out.println(exchange.getBody());
    }
    

结果:
结果

源码

gitee

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITdfq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值