背景
在一个项目中我使用restTemplate进行get请求,并在url中携带参数
String urlEncodedText = URLEncoder.encode(text, "UTF-8");
String url = "http://xxx?&word=" + urlEncodedText;
ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, null, byte[].class);
问题
发送请求时发现和预期不一样,发现restTemplate又自动进行了一次url编码。所以参数和预期不同。
结论
如果使用restTemplate发送请求,在url中携带参数,不需要再进行一次url编码
思考
感觉restTemplate帮用户省了很多事情,比如这次这个自动URL编码。还有MediaType的选择。这对于对方是比较现代的标准的接口是很方便的。但如果对方不是标准的,比如说MediaType不是常见的,没有设置。这时候restTemplate就显得不够灵活。这种情况下我觉得okhttp3也是一个不错的选择。
参考
https://www.cnblogs.com/shineman-zhang/articles/14071747.html
https://blog.youkuaiyun.com/Petershusheng/article/details/54236816
https://blog.youkuaiyun.com/blueheart20/article/details/80916517