java傳送http請求

惊朝發表於2024-04-27
    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());
        }
    }

相關文章