SpringBoot 整合 RestTemplate 实现远程调用接口

SpringBoot整合RestTemplate实现远程调用接口

简介:

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

RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如Apache HttpComponents、Netty或OkHttp等其它HTTP library。

其实spring并没有真正的去实现底层的http请求(3次握手),而是集成了别的http请求,spring只是在原有的各种http请求进行了规范标准,让开发者更加简单易用,底层默认用的是jdk的http请求。

RestTemplate的优缺点:

优点:
     连接池、超时时间设置、支持异步、请求和响应的编解码

缺点:
     依赖别的spring版块、参数传递不灵活

1. 创建springboot项目,我的项目结构
在这里插入图片描述

2.新建RestTemplate的配置类:

package com.example.demo.config;

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;

/**
 * RestTemplate配置类
 */
@Configuration
public class RestTemplateConfig {

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

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }


}

@Bean 将RestTemplate注入到spring容器中。

3.使用Test类来进行测试。
添加restTemplate依赖到测试类中:
在这里插入图片描述
测试一个GET请求,参数代码中有解释:

@Test
    void contextLoads() {
        /**
         * GET请求
         * 1)url: 请求地址;
         * 2)method: 请求类型(如:POST,PUT,DELETE,GET);
         * 3)requestEntity: 请求实体,封装请求头,请求内容
         * 4)responseType: 响应类型,根据服务接口的返回类型决定
         * 5)uriVariables: url中参数变量值
         */
        ResponseEntity<String> exchange = restTemplate.exchange("http://oapi.17car.vip", HttpMethod.GET, null, String.class);
        HttpStatus statusCode = exchange.getStatusCode();
        int statusCodeValue = exchange.getStatusCodeValue();
        String storeNumber = exchange.toString();
        String body = exchange.getBody();
        System.out.println(statusCode);
        System.out.println(statusCodeValue);
        System.out.println(storeNumber);
        System.out.println(body);

    }

结果:
在这里插入图片描述
使用exchange.getBody();即可得到json字符串,后续可以转换成对象进行业务处理。

附上:

说明:1)url: 请求地址;
2)method: 请求类型(如:POST,PUT,DELETE,GET);
3)requestEntity: 请求实体,封装请求头,请求内容
4)responseType: 响应类型,根据服务接口的返回类型决定
5)uriVariables: url中参数变量值

POST请求:

String reqJsonStr = "{\"code\":\"testCode\", \"group\":\"testGroup\",\"content\":\"testContent\", \"order\":1}";
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr,headers);
ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL, HttpMethod.POST, entity, Map.class);

PUT请求:

String reqJsonStr = "{\"id\":227,\"code\":\"updateCC\", \"group\":\"UPDATE\",\"content\":\"updateCT\", \"order\":9}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr,headers);
ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL, HttpMethod.PUT, entity, Map.class);

DELETE请求:

ResponseEntity<Map> resp = restTemplate.exchange(DIC_DATA_URL + "?id={id}", HttpMethod.DELETE, null, Map.class, 227);

RestTemplate主要的6个方法:
在这里插入图片描述

   delete() 在特定的URL上对资源执行HTTP DELETE操作
   
   exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中 映射得到的
   
   execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
   
   getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
   
   getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
   
   postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得
   到的
   
   postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
   
   headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
   
   optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
   
   postForLocation() POST 数据到一个URL,返回新创建资源的URL
   
   put() PUT 资源到特定的URL

参考博文:
https://blog.csdn.net/QiaoRui_/article/details/80453799

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值