使用 RestTemplate 调用 restful 服务详解程序员
2023-06-13 09:20:05 时间
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。
调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求,可以通过使用ClientHttpRequestFactory指定不同的HTTP请求方式。
ClientHttpRequestFactory接口主要提供了两种实现方式
RestTemplate默认是使用SimpleClientHttpRequestFactory,内部是调用jdk的HttpConnection,默认超时为-1
使用示例:import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class SpringbootRestTemplateApplication { // 启动的时候要注意,由于我们在controller中注入了RestTemplate,所以启动的时候需要实例化该类的一个实例 @Autowired private RestTemplateBuilder builder; // 使用RestTemplateBuilder来实例化RestTemplate对象,spring默认已经注入了RestTemplateBuilder实例 @Bean public RestTemplate restTemplate() { return builder.build(); public static void main(String[] args) { SpringApplication.run(SpringbootRestTemplateApplication.class, args); }编写controller
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.chhliu.springboot.restful.vo.User; @RestController public class RestTemplateController { @Autowired private RestTemplate restTemplate; @GetMapping("/template/{id}") public User findById(@PathVariable Long id) { //http://localhost:8080/user/ 是服务的对应的url User u = this.restTemplate.getForObject("http://localhost:8080/user/" + id,User.class); System.out.println(u); return u; }
相关文章
- Flask 学习-23.restful 接口开发
- Flask 学习-34.restful-full 请求参数自定义参数校验类型RequestParser
- Flask 学习-39.Flask-RESTful 请求参数校验inputs
- restful接口定义_主板上的spi接口接什么
- restful put post_RequestMappingHandlerMapping
- 接口测试第4讲:Restful API
- 【ES三周年】Elasticsearch原理深入浅出 — RESTful/ 倒排索引/ BKD树
- 安装和配置Go-RESTful框架
- Go-RESTful-创建RESTful API服务(二)
- Go-RESTful-创建RESTful API服务(三)
- java中RESTful 的实现框架详解架构师
- java开发RESTful接口代码示例详解架构师
- 基于SpringBoot开发一个Restful服务,实现增删改查功能详解编程语言