跳至主要內容

RestTemplate

chanchaw小于 1 分钟java

概述

案例

exchange

下面是通过 map 按照 key 将参数拼接到 url 后发送网络请求数据。注意依赖 HttpMethod 不要使用错,否则报错不存在该函数签名的重载方法 exchange

import cn.hutool.core.collection.CollUtil;
import org.springframework.http.HttpMethod;
import org.springframework.core.ParameterizedTypeReference;

// 1. 从对象集合获取主键集合
Set<Long> itemIds = vos.stream().map(CartVO::getItemId).collect(Collectors.toSet());
// 2.查询商品
Map<String, String> params = new HashMap<>();
params.put("ids", CollUtil.join(itemIds, ","));

ResponseEntity<List<ItemDTO>> res = restTemplate.exchange(
    "http://localhost:8081/item?ids={ids}",
    HttpMethod.GET,
    null,/* requestEntity - 本 get 请求,不需要传递请求体*/
    new ParameterizedTypeReference<List<ItemDTO>>(){},
    params
);