RestTemplate
Spring给我们提供了一个RestTemplate工具,可以方便的实现Http请求的发送。使用步骤如下:
注入RestTemplate到Spring容器
public RestTemplate restTemplate() {
return new RestTemplate();
}发起远程调用
public <T> ResponseEntity<T> exchange(
String url; //请求路径
HttpMethod method; //请求方式
HttpEntity<?> requestEntity; //请求实体
Class<T> responseType; //返回值类型
Map<String, ?> uriVariables //请求参数
)示例
ResponseEntity<List<ItemDTO>> response = restTemplate.exchange(
"http://localhost:8081/items?ids={ids}",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<ItemDTO>>() {
},
Map.of("ids", CollUtil.join(itemIds, ","))
);
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Awei的博客!
评论