如何在java代码中发送http请求(springcloud学习笔记1)

步骤:

  • 注册一个RestTemplate的实例到Spring容器

  • @MapperScan("cn.itcast.order.mapper")
    @SpringBootApplication
    public class OrderApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(OrderApplication.class, args);
        }
    
        /**
         * 创建RestTemplate并注入Spring容器
         * @return
         */
        @Bean
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }

  • 修改order-service服务中的OrderService类中的queryOrderById方法,根据Order对象中的userId查询User

  • @RestController
    @RequestMapping("order")
    public class OrderController {
    
       @Autowired
       private OrderService orderService;
    
        @GetMapping("{orderId}")
        public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
            // 根据id查询订单并返回
            return orderService.queryOrderById(orderId);
        }
    }

  • 将查询的User填充到Order对象,一起返回

  • @Service
    public class OrderService {
    
        @Autowired
        private OrderMapper orderMapper;
    
        @Autowired
        private RestTemplate restTemplate;
        public Order queryOrderById(Long orderId) {
            // 1.查询订单
            Order order = orderMapper.findById(orderId);
            // 2.利用RestTemplate发送http请求,查询用户
            // 2.1 url路径
            String url ="http://localhost:8081/user/"+order.getUserId();
            // 2.2 发送http请求 实现远程调用
            User user = restTemplate.getForObject(url, User.class);
            // 3.封装user到Order
            order.setUser(user);
            // 4.返回
            return order;
        }
    }

    测试一下成功

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值