SpringBoot 之RestTemplate的使用

RestTemplate介绍
  调用远程服务时就必须使用HTTP客户端,主要有四种:JDK原生的URLConnection、Apache的Http Client、Netty的异步HTTP Client, Spring的RestTemplate。  

  解放了原先HttpClient的复杂提交,java中调用RESTful服务很典型的是使用HttpClient,对于常用的REST操作,这些方法属于低等级的操作。使用HttpClient我们需要自己封装Post请求,再根据响应的状态码判断从响应中获取header和body,有时候还需要自己做json转换。

  Spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。

  在Spring应用程序中访问第三方REST服务与使用Spring RestTemplate类有关。RestTemplate类的设计原则与许多其他Spring *模板类(例如JdbcTemplate、JmsTemplate)相同,为执行复杂任务提供了一种具有默认行为的简化方法。

  RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。
其实spring并没有真正的去实现底层的http请求(3次握手),而是集成了别的http请求,spring只是在原有的各种http请求进行了规范标准,让开发者更加简单易用,底层默认用的是jdk的http请求。

  考虑到RestTemplate类是为调用REST服务而设计的,因此它的主要方法与REST的基础紧密相连就不足为奇了,后者是HTTP协议的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如,RestTemplate类具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。

RestTemplate的优缺点:
          优点:
                连接池、超时时间设置、支持异步、请求和响应的编解码
          缺点:
                依赖别的spring版块、参数传递不灵活

RestTemplate官方网站:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

一、依赖包

RestTemplate是spring的一个rest客户端,在spring-web这个包下,spring boot的依赖如下:

        <!--对全栈web开发的支持, 包括Tomcat和spring-webmvc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

点击spring-boot-starter-web依赖会打开spring-web

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.2.RELEASE</version>
      <scope>compile</scope>
    </dependency>

Get请求接口

    /**
     * 带参数,返回list集合的get请求
     * @return
     */
    @GetMapping("/getMethodHasParamReturnList")
    public ResponseEntity<List> getMethodHasParamReturnList(){
        Map<String,Object> param=new HashMap<>();
        param.put("pageNum",1);
        param.put("pageSize",2);
        HttpHeaders headers=new HttpHeaders();
        ResponseEntity<List> response = restTemplate.exchange(
                "http://127.0.0.1:8080/getPost/getMethodHasParamReturnList?pageNum={pageNum}&pageSize={pageSize}",
                HttpMethod.GET,
                new HttpEntity<String>(headers),
                List.class,
                param);
        System.out.println(response.getBody());
        return response;
    }

远程调用接口:

    /**
     * 带参数,返回list集合的get请求
     * @return
     */
    @GetMapping("/getMethodHasParamReturnList")
    public List<Student> getMethodHasParamReturnList(
        @RequestParam(value = "pageNum",required = false) Integer pageNum,
        @RequestParam(value = "pageSize",required = false) Integer pageSize){
        Student student1=new Student();
        student1.setId("2222");
        student1.setName("lisi");
        Student student2=new Student();
        student2.setId("3333");
        student2.setName("wangwu");
        List<Student> students=new ArrayList<>();
        students.add(student1);
        students.add(student2);
        return students;
    }

Post请求接口

    /**
     * post请求,带参数,返回list集合
     * @param
     * @return
     */
    @PostMapping("/postMethodReturnList")
    public List<Student> postMethodReturnList(){
        //请求头
        MediaType type=MediaType.parseMediaType("application/json");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        //请求参数
        Student student=new Student();
        student.setId("1111");
        student.setName("aaaa");
        //这里要把数据转为json格式才能传递
        Object param = JSON.toJSON(student);
        HttpEntity<String> formEntity = new HttpEntity<>(param.toString(), headers);
        ResponseEntity<List> responsebody = restTemplate.exchange(
                "http://127.0.0.1:8080/getPost/postMethodReturnList",
                HttpMethod.POST,
                formEntity,
                List.class);
        List<Student> body = responsebody.getBody();
        System.out.println(body);
        return body;
    }

远程请求接口:

    /**
     * post请求,带参数,返回list集合
     * @param student
     * @return
     */
    @PostMapping("/postMethodReturnList")
    public List<Student> postMethodReturnList(@RequestBody Student student){
        List<Student> students=new ArrayList<>();
        students.add(student);
        students.add(student);
        students.add(student);
        System.out.println(students);
        return students;
    }

参考文章:

https://www.cnblogs.com/h--d/p/12609753.html

https://blog.csdn.net/QiaoRui_/article/details/80453799

配置连接池比较好的文章

https://blog.csdn.net/umke888/article/details/54881946

https://www.cnblogs.com/likaitai/p/5431246.html

讲解比较好的文章

https://my.oschina.net/lifany/blog/688889

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot项目中使用RestTemplate可以方便地进行HTTP请求。你可以通过创建RestTemplate实例来使用它。在你提供的代码中,你展示了两种使用RestTemplate的方式。 第一种方式是通过自己创建RestTemplate实例并设置连接超时和读取超时的方式。你可以使用SimpleClientHttpRequestFactory来设置连接超时和读取超时的时间,然后将其设置为RestTemplate的请求工厂。这样就可以创建一个自定义配置的RestTemplate实例。 第二种方式是通过使用注解@Autowired将RestTemplate实例注入到你的代码中。这种方式需要在Spring Boot项目中配置RestTemplate的Bean,然后使用@Autowired注解将其注入到需要使用的地方。 RestTemplate提供了多种方法来发送HTTP请求,包括GET请求、POST请求、PUT请求、DELETE请求等。你可以根据需要选择合适的方法来发送请求。在你提供的代码中,展示了使用postForObject方法发送POST请求的示例。你可以指定请求的URL、请求的参数和返回结果的类型,然后使用postForObject方法发送请求并获取返回结果。 总之,Spring Boot中的RestTemplate是一个方便的HTTP请求工具,可以帮助你发送各种类型的HTTP请求。你可以根据需要选择合适的方式来使用RestTemplate。 #### 引用[.reference_title] - *1* [Springboot 使用RestTemplate](https://blog.csdn.net/qq_30938705/article/details/109804221)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot使用RestTemplate](https://blog.csdn.net/watson2017/article/details/124865399)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值