带有特殊字符的Springboot Rest模板查询参数



我通过java代码像这样调用api。

UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(myUrl);
builder.queryParam("sandwich","PB_&_J");
return restTemplate.exchange(builder.toUriString(),HttpMethod.GET,MyObject.class);

该参数为

的api服务
@GetMapping("myUrl")
MyObject myApiFunction( @RequestParam String sandwich){
log(sandwich);
//return something
}

没有正确地使用此请求(日志中有'%26'而不是'&')。

但是如果我打印builder. tourisstring (),这是http://myurl?sandwich=PB_%26_J并通过Postman命中它,api服务就会正确地消费它。

restTemplate怎么了?代码?

UriComponentsBuilder.toUriString()对其变量进行编码。https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html toUriString——

如果你想要你的参数不编码,那么构建未编码的URI,然后传递给RestTemplate。

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html构建——

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponents.html toUri——

例如,

restTemplate.exchange(builder.build().toUri(), HttpMethod.GET,MyObject.class);

可以传递未编码的uri。但是web浏览器请求编码的uri。所以,我建议你在制作完控制器后,在真实的浏览器中进行测试。

最新更新