当前位置:   article > 正文

编码出现+号,传到后端接口被替换成了空格问题解决_java 接收+被替换空格

java 接收+被替换空格

情况如下:

	public static void main(String[] args) {
				String orderDescription = "订购成功立即生效,30天内可观看专区中除单独计费影片外的所有内容,到期自动取消。";
		orderDescription = Base64.encode(orderDescription, "gbk");
		System.out.println(orderDescription);
		orderDescription = orderDescription.replace("+", "%2B");
		System.out.println(orderDescription);
		orderDescription = Base64.decodeStr(orderDescription, "gbk");
		System.out.println("==========================================");
		System.out.println(orderDescription);
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在这里插入图片描述

对这段中文进行编码后,出现了+号,导致,传给后端接口出现部分乱码现象
在这里插入图片描述
那么,导致这个问题的原因,就是Tomcat把+号换成了’ '空格。
这个是HTML规范中的规定,在这里算是个小坑,但是有不能说是bug

解决办法1:
对编码后的字符串进行替换

orderDescription = orderDescription.replace("+", "%2B");
  • 1

那么,到后端接口后,会自动把 %2B 替换回+号,于是,可以正常解码了

来看下JDK中处理方式:

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public static void main(String[] args) throws UnsupportedEncodingException {
        String testStr="space here";
        String afterEncode= URLEncoder.encode(testStr,"UTF-8");
        System.out.println("1.beforeEncode: " + testStr);
        System.out.println("2.afterEncode: "+afterEncode);
        String afterDecode= URLDecoder.decode(afterEncode,"UTF-8");
        System.out.println("3.afterDecode: "+afterDecode);
        String replace = afterEncode.replace("+", "%20");
        System.out.println("4.replace: "+replace);
        String replaceDecode = URLDecoder.decode(replace, "UTF-8");
        System.out.println("5.replaceDecode: "+replaceDecode);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

在这里插入图片描述

参考:
这一篇讲的非常详细,提出了三种解决方案
https://www.cnblogs.com/thisiswhy/p/12119126.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/639785
推荐阅读
相关标签
  

闽ICP备14008679号