RestTemplate使用

Posted ITdfq

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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());
    }
    

结果:
结果

以上是关于RestTemplate使用的主要内容,如果未能解决你的问题,请参考以下文章

RestTemplate

RestTemplate--解决中文乱码

使用RestTemplate在代码内调用POST请求的参数乱码问题

RestTemplate使用

springboot使用restTemplate post提交值 restTemplate post值

Spring RestTemplate 专题