Java URLEncoder 编码空格为“+”

使用java.net.URLEncoder编码字符串后会将空格替换为+,导致验签出错或前端不能还原原字符串的空格。

String s = "文件 -文件1";
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);

结果为:%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

URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20");

(2)使用其他类库的方法,例如Spring的UriUtils

UriUtils.encode(fileName, StandardCharsets.UTF_8.name());

参考:https://stackoverflow.com/questions/4737841/urlencoder-not-able-to-translate-space-character

上一篇 Spring Boot配置Cors解决跨域请求问题
下一篇 Java原生JSONObject实现JSON串与Java对象互转
目录
文章列表
1 MyBatis mybatis-generator配置
MyBatis mybatis-generator配置
2
使用 Spring Boot Actuator 监控应用
使用 Spring Boot Actuator 监控应用
3
微信境外服务商支付
微信境外服务商支付
4
Flutter Widget之GridView
Flutter Widget之GridView
5
React Native学习之PanResponder手势识别
React Native学习之PanResponder手势识别
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。