java发送http请求

    private void handleCartItems(List<CartVO> vos) {
        // 1.获取商品id
        Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());
        // 2.查询商品
        ResponseEntity<List<ItemDTO>> response = restTemplate.exchange(  //  发送http请求
                "http://localhost:8081/items?ids={ids}",    //  URL
                HttpMethod.GET, //  get请求
                null,   //  null表示没有提供HttpHeaders(请求头)和HttpEntity(请求体)作为请求的正文
//  下面这行本来是传一个class的字节码,但是我需要的是一个ItemDTO类型的List,所以字节码就不行了
//  所以采用new一个ParameterizedTypeReference,并把对象类型放到尖括号里面,不能写List<ItemDTO>.class哦,没有这种写法
                new ParameterizedTypeReference<List<ItemDTO>>() {}, //  响应体
                Map.of("ids", CollUtils.join(itemIds, ","))
//  使用Map.of创建一个包含单个键值对的不可变Map。键是"ids",值是通过CollUtils.join(itemIds, ",")方法生成的
//  这个方法将itemIds列表中的元素用逗号连接成一个字符串。
        );
            //  解析http请求
        if(!response.getStatusCode().is2xxSuccessful())     return; //  如果2xx状态码不成功,直接结束
        List<ItemDTO> items = response.getBody();

        if (CollUtils.isEmpty(items)) {
            return;
        }
        // 3.转为 id 到 item的map
        Map<Long, ItemDTO> itemMap = items.stream().collect(Collectors.toMap(ItemDTO::getId, Function.identity()));
        // 4.写入vo
        for (CartVO v : vos) {
            ItemDTO item = itemMap.get(v.getItemId());
            if (item == null) {
                continue;
            }
            v.setNewPrice(item.getPrice());
            v.setStatus(item.getStatus());
            v.setStock(item.getStock());
        }
    }
posted @ 2024-04-27 17:27  惊朝  阅读(1)  评论(0编辑  收藏  举报