RestTemplate使用

RestTemplate使用

仓库地址:https://gitee.com/yun2333/rest-template.git

1、什么是RestTemplate

官网https://docs.spring.io/spring-framework/docs/6.0.11/javadoc-api/org/springframework/web/client/RestTemplate.html
RestTemplate是一款Spring框架中的HTTP客户端工具类库,它封装了大量的HTTP请求处理代码,使得我们可以方便地进行HTTP请求的发送与处理。RestTemplate支持多种HTTP请求方式,例如GET、POST、PUT、DELETE等,同时也支持参数的传递与响应结果的解析等功能,使得我们在进行RESTful风格的API开发时更加方便。
在实际开发中需要调用第三方接口数据,或者是调用另外一个服务接口时,我们可以使用spring 框架提供的 RestTemplate 类可用于在应用中调用 rest 服务,它简化了与 http 服务的通信方式,统一了 restful 的标准,封装了 http 链接, 我们只需要传入 url 及返回值类型即可。
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
RestTemplate优点:

  • RestTemplate属于spring的,假如springboot项目的话,完全不用引入任何其他依赖,直接可以用。

RestTemplate可以和cloud当中的ribbon进行配合使用,只需要一个注解就可以完成负载均衡调用。

2、RestTemplate的使用

RestTemplate的使用分为俩种方式,一种是spring环境,一种是非spring环境

2.1 非spring环境

2.1.1 导依赖
#如果当前项目不是Spring项目,加入spring-web包,即可引入RestTemplate类
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>5.2.6.RELEASE</version>
</dependency>

2.1.2 业务
当在非spring环境下需要使用resttemplate时,只需要使用New获取到restTmeplate的实例,然后再进行之后所需要的收发Http请求的操作即可。使用new的形式获取到RestTemplate的实例,以发送get请求为例进行测试:
public void simpleTest() {
   
    RestTemplate restTemplate = new RestTemplate();
    String url = "";
    String str = restTemplate.getForObject(url, String.class);
    System.out.println(str);
}

2.2 spring环境

2.2.1 添加pom依赖
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2.2 添加RestTemplate配置类
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;
 
/**
 * @program: RestTemplate
 * @description:
 * @author: DingZhenYun
 * @create: 2024-04-18 16:37
 **/

@Configuration//加上这个注解作用,可以被Spring扫描
public class RestTemplateConfig {
   

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

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
   
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        //并设置连接和请求的时间
        factory.setReadTimeout(500000);//单位为ms
        factory.setConnectTimeout(500000);//单位为ms
        return factory;
    }
}

2.2.3 案例
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
 
import java.util.Map;
 
/**
 * RestTemplate Use Example Demo
 *
 */
@Controller
public class RestTemplateCtrl {
   
    @Autowired
    private RestTemplate restTemplate;
 
    /**
     * exchange()形式
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/resttemplate/getNative", method = RequestMethod.GET)
    public String restTemplateNativeTest(Map data) {
   
        // 请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<Object> httpEntity = new HttpEntity<>(data, httpHeaders);
        String url = "";
        // 发送请求
        ResponseEntity entity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        // 获取请求回调
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSON(entity.getBody()).toString());
        // 打印请求返回信息
        return jsonObject.toJSONString();
    }
 
    /**
     * execute()形式
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/resttemplate/getreqAndrep", method = RequestMethod.GET)
    public String restTemplateTest(Map data) {
   
        // 请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<Object> httpEntity = new HttpEntity<>(httpHeaders);
        // 请求提取器
        RequestCallback requestCallback = restTemplate.httpEntityCallback(httpEntity, Map.class);
        // 响应提取器
        ResponseExtractor<ResponseEntity<Map>> responseExtractor = restTemplate.responseEntityExtractor(Map.class);
        String url = "";
        // 发送请求
        ResponseEntity entity = restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor, data);
        // 获取请求回调
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSON(entity.getBody()).toString());
        // 打印请求返回信息
        return jsonObject.toJSONString();
    }
 
}

3、使用

3.1 get方法


这里的方法一共有两类,getForEntity 和 getForObject,每一类有三个重载方法
两者只是在返回结果接收的时候略有差别。getForObject 和 getForEntity 的差异,这两个的差异主要体现在返回值的差异上, getForObject 的返回值就是服务提供者返回的数据,使用 getForObject 无法获取到响应头。

参数 说明
String url 请求接口地址
URI url 使用 Uri 对象时,参数可以直接拼接在地址中
Class responseType 返回的response当中body的对象类型,相当于只要这块写好了,我们就不用将返回值 再进行序列化成对象了。
Map<String,?> uriVariables map类型的key value参数,这个key需要和地址当中的key相对应的
Object… uriVariables 这是一个可变长参数,地址栏当中可以用1,2数字占位符当中参数,传参的时候,只要这块的可变长参数能按顺序和占位符 一 一对上即可。

3.1.1 普通get请求
  • 上游接口
@RestController
@RequestMapping("/up")
public class UpstreamController {
   

    @GetMapping("/get")
    public UseDto get() {
   
        return new UseDto(1, "大家好,我是ikun",22);
    }
}

3.1.1.1 getForEntity
@Resource
    private RestTemplate restTemplate;

    private static final String SERVICE_PROVIDER = "http://localhost:4000";
    @GetMapping("/get1")
    public UseDto get1() {
   
        return restTemplate.getForObject(SERVICE_PROVIDER + "/up/get", UseDto.class);
    }
接口打印
{
   
    "id": 1,
    "name": "大家好,我是ikun",
    "age": 22
}

3.1.1.2 getForObject
@GetMapping("/get2")
    public UseDto get2() {
   
        //getForEntity方法,返回值为ResponseEntity类型
        // ResponseEntity中包含了响应结果中的所有信息,比如头、状态、body
        ResponseEntity<UseDto> responseEntity = restTemplate.getForEntity(SERVICE_PROVIDER + "/up/get", UseDto.class);
        //状态码
        log.info("状态码:{}",responseEntity.getStatusCode());
        log.info("头:{}",responseEntity.getHeaders());
        //获取body
        UseDto dto = responseEntity.getBody
  • 25
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值