使用RestTemplate发送get请求,获取不到参数的问题

错误案例

使用RestTemplate发送GET请求,发现后端接收不到请求参数

1
2
3
4
5
6
7
String url = "http://api.xxx.xxx";
//模拟请求参数
Map map = new HashMap<>();
map.put("name", "Joe.Ye");
map.put("age", "18");

String result = restTemplate.getForObject(url, String.class, map);

发现一直拿不到name和age

正确姿势

URL拼接query参数

1
String url = "http://api.xxx.xxx?name={name}&age={age}";

UriCompoentBuilder方式(优雅、推荐)

1
2
3
4
5
6
7
8
HttpHeaders headers = new HttpHeaders();
headers.add("accept", "*/*");
HttpEntity<JSONObject> httpEntity = new HttpEntity<JSONObject>(null, headers);

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("id", "10");

ResponseEntity<JSONObject> response = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, httpEntity, JSONObject.class);
1
2
3
4
5
6
7
8
9
10
11
12
13
String url = "https://www.appblog.cn";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
String url2 = builder.queryParam("name", "Joe.Ye").build().encode().toString();
System.out.println("url2 = " + url2); //https://www.appblog.cn?name=Joe.Ye

Map<String,String> param = Maps.newHashMap();
param.put("name", "Joe.Ye");
param.put("age", "18");
param.entrySet().stream().forEach(o -> builder.queryParam(o.getKey(),o.getValue()));
String url3 = builder.build().encode().toString(); //https://www.appblog.cn?name=Joe.Ye&age=18
System.out.println("url3 = " + url3);

//ResponseEntity<String> rsp = restTemplate.getForEntity(url3, String.class);

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2021 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :