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

错误案例

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

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参数

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

UriCompoentBuilder方式(优雅、推荐)

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);
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);

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/11/spring-boot-use-resttemplate-to-send-get-request-but-cannot-obtain-parameters/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Spring Boot使用RestTemplate发送get请求,获取不到参数的问题
错误案例 使用RestTemplate发送GET请求,发现后端接收不到请求参数 String url = "http://api.xxx.xxx"; //模拟请求参数 Map map = new HashMap<……
<<上一篇
下一篇>>
文章目录
关闭
目 录