Spring boot restTemplate

本文详细介绍了Spring Boot中RestTemplate的使用,包括其重要参数、GET、POST、PUT、DELETE操作的传参方式,以及如何进行Form表单提交和文件上传。同时,文章还探讨了如何配置RestTemplate使用HttpClient和OkHttp,并介绍了如何添加请求拦截器以记录请求详情和时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring boot restTemplate

上一节 spring boot 数据库连接池

spring boot 数据库连接池

源码

源码地址


Spring boot restTemplate

简介
restTemplate 是spring 提供的进行http 访问的工具;spring boot 中已经配置好了;

springboot 中 对 restTemplate 的支持

在 RestTemplateAutoConfiguration 中可以看到 已经创建了 bean, RestTemplateBuilder (注意springboot版本,我的为2.1.6)

	@Bean
   @ConditionalOnMissingBean
   public RestTemplateBuilder restTemplateBuilder() {
   
   	RestTemplateBuilder builder = new RestTemplateBuilder();
   	HttpMessageConverters converters = this.messageConverters.getIfUnique();
   	if (converters != null) {
   
   		builder = builder.messageConverters(converters.getConverters());
   	}

   	List<RestTemplateCustomizer> customizers = this.restTemplateCustomizers.orderedStream()
   			.collect(Collectors.toList());
   	if (!CollectionUtils.isEmpty(customizers)) {
   
   		builder = builder.customizers(customizers);
   	}
   	return builder;
   }

在项目中使用,配置RestTemplate

添加配置类, 配置 restTemplate

@Configuration
@ConditionalOnClass(RestTemplate.class)
public class RestTemplateConfig {
   
@Bean
 public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
   
     return restTemplateBuilder
     // 配置 readTimeout
     .setReadTimeout(Duration.ofSeconds(5))
     // 配置 连接超时
     .setConnectTimeout(Duration.ofSeconds(2)).build();
 }

}

项目中使用 只需要引入一下即可

    @Autowired
    private RestTemplate restTemplate;

restTemplate 重要参数

url: 请求地址
responseType: 返回值类型
uriVariables: url 变量值
Object request: 请求体;可以是个httpEntity;若为其他,则会创建一个httpEntity ,request为 httpEntity 的body
HttpEntity: 请求参数,可以设置body, headers
responseEnity: 请求返回值,包含具体的body, headers, httpstatus 等http信息

restTemplate GET POST PUT DELETE 操作 传参

get 请求

  • getForObject
// 接收url 和 responseType
restTemplate.getForObject(JDBC_DEMO_URL + "/user/" + id, UserEntity.class);
// url传参; 使用 模板占位符 {index};进行传参,Object... uriVariables 按照index顺序进行传参
// 例如 url = /user/batch?ids={0}&ids={1}, 参数 uriVariables可变数组按照顺序传参;
// 注意: 这里的 collect 是我封装好的 = ‘?ids={index}’;例如   /user/batch?ids={0}&ids={1}
restTemplate.getForObject(JDBC_DEMO_URL + "/user/batch" + collect, List.class, ids);
// url传参, 同时模板占位符 {feild}进行传参, 使用 map  uriVariables 进行参数赋值
// 例如  url = /user/batch?uName={name}&password={password};
// params = new Map(); put(name,name),put(password,password)
restTemplate.getForObject(JDBC_DEMO_URL + "/user/batch" + collect, List.class, params);
  • getForEntity
    getForEntity 和 getForObject 使用方式一样;只是返回的类型不一样;
    getForEntity 返回 responseEntity, 可以有更具体的信息, body, headers, httpstatus 等信息;

ForENtity 和ForObject 请求使用是一样的 只是返回值不同;以下只使用其中的一种。


Post 请求

postForObject

     public List<String> batchAddUser(@RequestBody List<UserEntity> userEntities) throws Exception {
   
        return restTemplate.postForObject(JDBC_DEMO_URL + "/user/batch", userEntities, List.class);
    }

参数userEntities; 是请求体,会封装到httpEntity 的body中;

post 请求的所有方法: 具体的参数可以参考restTemplate 重要参数
在这里插入图片描述

Put 请求

 restTemplate.put(JDBC_DEMO_URL + "/user", userEntity);

delete 请求

  Map<String, String> map = new HashMap<>();
        map.put("id", id);
        // 使用{field}占位符,进行参数映射
        restTemplate.delete(JDBC_DEMO_URL + "/user/{id}", map
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值