49 lines
1.7 KiB
Markdown
49 lines
1.7 KiB
Markdown
|
## 使用RestTemplate优雅的发送Get请求
|
|||
|
|
|||
|
在我们的项目中,如果借助 [RestTemplate](https://so.csdn.net/so/search?q=RestTemplate&spm=1001.2101.3001.7020) 发送带参数的 Get 请求,我们可以通过拼接字符串的方式将 url 拼接出来,比如下面这种方式:
|
|||
|
|
|||
|
```java
|
|||
|
String url = "http://127.0.0.1:8080/rest/get? + id;
|
|||
|
ResponseEntity<RestVO> forEntity = restTemplate.getForEntity(url, RestVO.class);
|
|||
|
```
|
|||
|
|
|||
|
然而这种方式不太优雅,我们还可以通过以下几种方式发送 Get 请求
|
|||
|
|
|||
|
#### 方式 1:使用占位符
|
|||
|
|
|||
|
```java
|
|||
|
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 `中的占位符一致
|
|||
|
|
|||
|
#### 方式 2:使用 LinkedMultiValueMap 和 UriComponentsBuilder
|
|||
|
|
|||
|
```java
|
|||
|
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();
|
|||
|
```
|
|||
|
|
|||
|
方式 2 看起来是最优雅的,将参数的设置和 `url `分离。
|
|||
|
|
|||
|
#### Map 转 MultiValueMap
|
|||
|
|
|||
|
```java
|
|||
|
Map<String,String> params = new HashMap<>();
|
|||
|
MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>(
|
|||
|
params.entrySet().stream().collect(
|
|||
|
Collectors.toMap(Map.Entry::getKey, e -> Collections.singletonList(e.getValue()))));
|
|||
|
```
|
|||
|
|