RestTemplate优雅的发送Get请求(并拼接参数)

前言

在我们的项目中,如果借助RestTemplate发送带参数的Get请求,我们可以通过拼接字符串的方式将url拼接出来,比如下面这种方式:

String url = "http://127.0.0.1:8080/rest/get?name="+ name +"&id=" + id;
ResponseEntity<RestVO> forEntity = restTemplate.getForEntity(url, RestVO.class);

然而这种方式不太优雅,我们还可以通过以下几种方式发送Get请求

方式一:使用占位符

String url = "http://127.0.0.1:8080/rest/path/{name}/{id}";
Map<String, Object> params = new HashMap<>();
params.put("name", "这是name");
params.put("id", 1L);
ResponseEntity<RestVO> forEntity = restTemplate.getForEntity(url, RestVO.class, params);

Map的key要和url中的占位符一致

方式二:使用LinkedMultiValueMap和UriComponentsBuilder

String url = "http://127.0.0.1:8080/rest/get";
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("name", "这是name");
params.add("id", "1");
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = builder.queryParams(params).build().encode().toUri();
 
ResponseEntity<RestVO> forEntity = restTemplate.getForEntity(uri, RestVO.class);
return forEntity.getBody();

 

posted @   xiexie0812  阅读(2512)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示