代码可参考git:https://gitee.com/juncaoit/restsend
一:说明
1.介绍
spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接,我们只需要传入url及返回值类型即可。相较于之前常用的httpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如Apache HttpComponents、Netty或OkHttp等其它HTTP library。
2.为什么需要重新定制
RestTemplate是Spring自带的一个调用rest服务的客户端,它提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
RestTemplate默认是使用JDK原生的URLConnection,默认超时为-1, 也就表示是没有超时时间的,这个肯定不能满足复杂情况的使用需求, restTemplate的工厂是支持使用HttpClient和OkHttp来作为客户端实现的
3.为什么要使用连接池
在调用rest请求时,每次请求都需要和服务端建立连接,也就是三次握手,这是一个费时费力的工作,如果我们需要频繁对一个服务端进行调用,难道需要一直去建立连接吗?
所以使用连接池,可以避免多次建立连接的操作,节省资源开支
4.依赖
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.7</version> </dependency> <!--为了使用@ConfigurationProperties,还需要这个依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> <version>${springboot.version}</version> </dependency>
二:原生程序
1.直接使用
public class RestTemplateTest { public static void main(String[] args) { RestTemplate restT = new RestTemplate(); //通过Jackson JSON processing library直接将返回值绑定到对象 Quote quote = restT.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); String quoteString = restT.getForObject("http://gturnquist-quoters.cfapps.io/api/random", String.class); System.out.println(quoteString); } }
2.springboot使用
@SpringBootApplication public class HelloSpringBoot { public static void main(String[] args) { SpringApplication.run(HelloWorld.class, args); } @Bean public RestTemplate restTemplate(RestTemplateBuilder builder) { return builder.build(); } }
使用
@Service public class RestTemplateService { @Autowired RestTemplate restTemplate; public Quote someRestCall(){ return restTemplate.getForObject("http://gturnquist-quoters.cfapps.io/api/random", Quote.class); } }
分类:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)