springboot RestTemplate get请求参数中加号变成空格问题

看到问题,要寻其本质,切莫只求表面的结果

RestTemplate rest = new RestTemplateBuilder().build();
Map<String,String> m = new HashMap<>();
m.put("args","abc+124");
rest.getForEntity("http://xxx",Object.class,m);

以上代码,后台接收到的参数是“abc 124”,加号变成了空格。

遇到这个问题,不少人都会进行,特殊字符的替换,然后再在后端替换回来。

实际上,国内不少论坛的帖子也是这么写的。

所以,除非知道些质量高的论坛,还是搜外文网站,看结果吧。

Encoding of URI Variables on RestTemplate [SPR-16202]

A simpler solution is to set the encoding mode on the URI builder to VALUES_ONLY

DefaultUriBuilderFactory builderFactory = new DefaultUriBuilderFactory();
builderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);
RestTemplate rest = new RestTemplateBuilder()
.rootUri("http://xxx")
.uriTemplateHandler(builderFactory)
.build();

用这种方式构造RestTemplate,加号就不会丢了。

posted @ 2022-06-01 15:14  靛蓝代码  阅读(1240)  评论(0编辑  收藏  举报