栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot使用RestTemplate(基于2.6.7,返回泛型)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot使用RestTemplate(基于2.6.7,返回泛型)

一、示例依赖
  
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.alibaba.fastjson2
            fastjson2
            2.0.3.android
        
    
二、将RestTemplate加入spring管理
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class BeanConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        RestTemplate restTemplate = new RestTemplate(factory);
        return restTemplate;
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //建⽴连接所⽤的时间,适⽤于⽹络状况正常的情况下,两端连接所⽤的时间。单位毫秒
        factory.setConnectTimeout(15000);
        //建⽴连接后从服务器读取到可⽤资源所⽤的时间。单位毫秒
        factory.setReadTimeout(5000);
        return factory;
    }
}
三、请求基础数据
server.port=8089
import lombok.Data;

@Data
public class Student {
    private String name;
    private Integer age;

}
import lombok.Data;

@Data
public class Teacher {
   private String name;
   private String phone;
}

 准备两个请求,一个get一个post

#get地址
http://localhost:8089/test/getTeacherByStudnetId
#post地址
http://localhost:8089/test/saveStudent
http://localhost:8089/test/saveStudent2

import com.minos.resttemplete.bean.Student;
import com.minos.resttemplete.bean.Teacher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {
    
    @GetMapping("/getTeacherByStudnetId")
    public Teacher getTeacher(Long studentId) {
        System.out.println("根据学生:" + studentId + "查询老师");
        Teacher teacher = new Teacher();
        teacher.setName("xxx老师");
        teacher.setPhone("13113113152");
        return teacher;
    }
    
    @PostMapping("/saveStudent")
    public Student addStudnet(Student student) {
        System.out.println(student.toString());
        return student;
    }
    
    @PostMapping("/saveStudent2")
    public Student addStudnet2(@RequestBody Student student) {
        System.out.println(student.toString());
        return student;
    }
}

 四、RestTemplate之get请求 1、getForObject
 @Autowired
    RestTemplate restTemplate;
 @Test
    void testGetForObject() {
        String url = "http://localhost:8089/test/getTeacherByStudnetId";
        Map paramMap = new HashMap<>();
        paramMap.put("studentId", 5L);
        //只能返回响应体
        Teacher teacher = restTemplate.getForObject(url, Teacher.class, paramMap);
        System.out.println(JSON.toJSONString(teacher));
        //    {"name":"xxx老师","phone":"13113113152"}
    }
  

2、 getForEntity
 @Autowired
    RestTemplate restTemplate;

@Test
    void testGetForEntity() {
        String url = "http://localhost:8089/test/getTeacherByStudnetId?studentId=1";
        Map paramMap = new HashMap<>();
        paramMap.put("studentId", 5L);
        //返回形体、http头信息、http状态
        ResponseEntity forEntity = restTemplate.getForEntity(url, Teacher.class, paramMap);
        HttpStatus statusCode = forEntity.getStatusCode();
        int statusCodeValue = forEntity.getStatusCodeValue();
        Teacher teacher = forEntity.getBody();
        HttpHeaders headers = forEntity.getHeaders();
        System.out.println(JSON.toJSONString(statusCode));
        System.out.println(JSON.toJSONString(statusCodeValue));
        System.out.println(JSON.toJSONString(teacher));
        System.out.println(JSON.toJSONString(headers));
        //    "OK"
        //200
        //{"name":"xxx老师","phone":"13113113152"}
        //{"Content-Type":["application/json"],"Transfer-Encoding":["chunked"],"Date":["Wed, 18 May 2022 01:39:01 GMT"],"Keep-Alive":["timeout=60"],"Connection":["keep-alive"]}
    }
五、RestTemplate之post请求
@Autowired
    RestTemplate restTemplate;
    
 @Test
    void testPosttForObject1_1() {
        String url = "http://localhost:8089/test/saveStudent";
        Student stu = new Student();
        stu.setName("zhangsan");
        stu.setAge(50);
        //只能返回响应体
        Student student = restTemplate.postForObject(url, stu, Student.class);
        System.out.println(JSON.toJSONString(student));
        //    {}
    }

    @Test
    void testPosttForObject1_2() {
        String url = "http://localhost:8089/test/saveStudent";
        MultiValueMap paramMap = new LinkedMultiValueMap<>();
        paramMap.add("name", "zhangsan2");
        paramMap.add("age", 15);
        //只能返回响应体
        Student student = restTemplate.postForObject(url, paramMap, Student.class);
        System.out.println(JSON.toJSONString(student));
        //    {"age":15,"name":"zhangsan2"}
    }

    @Test
    void testPostForEntity1() {
        String url = "http://localhost:8089/test/saveStudent";
        MultiValueMap paramMap = new LinkedMultiValueMap<>();
        paramMap.add("name", "zhangsan2");
        paramMap.add("age", 15);
        //返回形体、http头信息、http状态
        ResponseEntity studentResponseEntity = restTemplate.postForEntity(url, paramMap, Student.class);
        System.out.println(JSON.toJSONString(studentResponseEntity.getStatusCode()));
        System.out.println(JSON.toJSONString(studentResponseEntity.getStatusCodeValue()));
        System.out.println(JSON.toJSONString(studentResponseEntity.getHeaders()));
        System.out.println(JSON.toJSONString(studentResponseEntity.getBody()));
        //    "OK"
        //200
        //{"Content-Type":["application/json"],"Transfer-Encoding":["chunked"],"Date":["Wed, 18 May 2022 01:37:01 GMT"],"Keep-Alive":["timeout=60"],"Connection":["keep-alive"]}
        //{"age":15,"name":"zhangsan2"}

    }

    @Test
    void testPosttForObject2_1() {
        String url = "http://localhost:8089/test/saveStudent2";
        Student stu = new Student();
        stu.setName("zhangsan");
        stu.setAge(50);
        //只能返回响应体
        Student student = restTemplate.postForObject(url, stu, Student.class);
        System.out.println(JSON.toJSONString(student));
    }

    @Test
    void testPosttForObject2_2() {
        String url = "http://localhost:8089/test/saveStudent2";
        HttpHeaders headers = new HttpHeaders();
        //设置请求头为json
        headers.setContentType(MediaType.APPLICATION_JSON);
        Student stu = new Student();
        stu.setName("zhangsan");
        stu.setAge(50);
        HttpEntity request = new HttpEntity<>(stu, headers);
        //只能返回响应体
        Student student = restTemplate.postForObject(url, request, Student.class);
        System.out.println(JSON.toJSONString(student));
        //    {"age":50,"name":"zhangsan"}
    }

    @Test
    void testPostForEntity2() {
        String url = "http://localhost:8089/test/saveStudent2";
        HttpHeaders headers = new HttpHeaders();
        //设置请求头为json
        headers.setContentType(MediaType.APPLICATION_JSON);
        Student stu = new Student();
        stu.setName("zhangsan");
        stu.setAge(50);
        HttpEntity request = new HttpEntity<>(stu, headers);
        //返回形体、http头信息、http状态
        ResponseEntity studentResponseEntity = restTemplate.postForEntity(url, request, Student.class);
        System.out.println(JSON.toJSONString(studentResponseEntity.getStatusCode()));
        System.out.println(JSON.toJSONString(studentResponseEntity.getStatusCodeValue()));
        System.out.println(JSON.toJSONString(studentResponseEntity.getHeaders()));
        System.out.println(JSON.toJSONString(studentResponseEntity.getBody()));
        //"OK"
        //200
        //{"Content-Type":["application/json"],"Transfer-Encoding":["chunked"],"Date":["Wed, 18 May 2022 01:38:00 GMT"],"Keep-Alive":["timeout=60"],"Connection":["keep-alive"]}
        //{"age":50,"name":"zhangsan"}

    }
六、RestTemplatelUtil工具类

可以返回泛型参数

@Component
public class RestTemplatelUtil {
    @Autowired
    RestTemplate restTemplate;
    
    public   T exchange(String url, HttpMethod method, ParameterizedTypeReference responseBodyType, A requestBody) {
        RestTemplate restTemplate = new RestTemplate();
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
        MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
        // 请求体
        headers.setContentType(mediaType);
        // 发送请求
        HttpEntity entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity resultEntity = restTemplate.exchange(url, method, entity, responseBodyType);
        return resultEntity.getBody();
    }
}

 使用方法

    public ResponseToken getToken() {
        //构造请求参数数据
        RequestData requestData = new RequestData();
        RequestLogin login = new RequestLogin();
        requestData.setData(login);
        //URL
        String url = RequestConstantsUrl.thloginUrl;
        //发起请求
        ResponseData exchange = restTemplatelUtil.exchange(url, HttpMethod.POST, new ParameterizedTypeReference>() {
        }, requestData);
        //获取数据
        return exchange.getReturnData();
    }

总结:

1、xxForObject和xxForEntity区别:xxForObject返回返回体,xxForEntity返回http头部信息、http状态码、返回体。一般使用xxForEntity,判断getStatusCodeValue()为200时候,再getBody;

2、post请求和get请求,第一个参数都是URL,第二个参数post是请求的参数,get是返回接受的类;第三个参数post是返回接受的类,get是请求的参数。

restTemplate.postForEntity(url, request, Student.class);
restTemplate.getForEntity(url, Teacher.class, paramMap);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/913695.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号