使用java.net.URLEncoder
编码字符串后会将空格替换为+
,导致验签出错或前端不能还原原字符串的空格。
1 | String s = "文件 -文件1"; |
结果为:%E6%96%87%E4%BB%B6+-%E6%96%87%E4%BB%B61
,空格被替换为+
,而不是%20
,JS使用DecodeURIComponent
得到文件+-文件1
。
查看源码可得java.net.URLEncoder
实现的是`application/x-www-form-urlencoded: https://www.w3.org/TR/html4/interact/forms.html#h-17.13.4。
处理方式为:
(1)使用String的replace
1 | URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"); |
(2)使用其他类库的方法,例如Spring的UriUtils
1 | UriUtils.encode(fileName, StandardCharsets.UTF_8.name()); |
参考:https://stackoverflow.com/questions/4737841/urlencoder-not-able-to-translate-space-character