大家好我是苏麟 今天带来Rest Template .
spring框架中可以用restTemplate
来发送http连接请求, 优点就是方便.
Rest Template 使用
Rest Template 使用步骤
/*** RestTemple:* 1.创建RestTemple类并交给IOC容器管理* 2. 发送http请求的类*/
1.注册RestTemplate对象
@SpringBootApplication
public class OrderApplication {public static void main(String[] args) {SpringApplication.run(OrderApplication.class, args);}/*** 创建RestTemple类并交给IOC容器管理** @RestTemple 是发送http请求的类** @LoadBalanced 负载均衡注解*/@Bean@LoadBalancedpublic RestTemplate restTemplate() {return new RestTemplate();}
}
2.发送HTTP请求
@Service
public class OrderService {@Autowiredprivate OrderMapper orderMapper;//引入@Autowiredprivate RestTemplate restTemplate;public Order queryOrderById(Long orderId) {// 1.查询订单Order order = orderMapper.findById(orderId);//2.利用RestTemplate发起http请求,查询用户信息//2.1 urlString url = "http://userserver/user/" + order.getUserId();//2.2 发送http请求,实现远程调用User u = restTemplate.getForObject(url, User.class);//3.封装到order里order.setUser(u);// 4.返回return order;}
}
主要代码就是
//2.利用RestTemplate发起http请求,查询用户信息//2.1 urlString url = "http://userserver/user/" + order.getUserId();//2.2 发送http请求,实现远程调用restTemplate.getForObject(url, User.class);
发送Get请求用 getForObject
参数: 第一个参数: 发送请求的路径 , 第二个参数 : 返回的类型
发送Post请求 postForObject
参数: 第一个参数: 发送请求的路径 , 第二个参数 : 请求数据对象 , 第三个参数 : 返回的类型
这期就到这里下期见!