快捷搜索: 王者荣耀 脱发

Base64中文乱码解决方法

1.什么是base64编码

由于一些网络通讯协议的限制,你必须使用 window.btoa() 方法对原数据进行编码后,才能进行发送。接收方使用相当于 window.atob() 的方法对接受到的 base64 数据进行解码,得到原数据。

例如,发送某些含有 ASCII 码表中 0 到 31 之间的控制字符的数据。 然而,window.btoa 与 window.atob 不支持中文,对于 unicode 编码的字符进行 base64 编码之后,通过浏览器原生的 btoa 方法界面中文会乱码。

2.JS中的base64的中文乱码解决方法

首先引入两个方法:utf16to8、utf8to16

function utf16to8(str) {
		  var out, i, len, c;
		
		  out = "";
		  len = str.length;
		  for(i = 0; i < len; i++) {
		    c = str.charCodeAt(i);
		    if ((c >= 0x0001) && (c <= 0x007F)) {
		      out += str.charAt(i);
		    } else if (c > 0x07FF) {
		      out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
		      out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
		      out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
		    } else {
		      out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
		      out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
		    }
		  }
		  return out;
	}

	function utf8to16(str) {
		  var out, i, len, c;
		  var char2, char3;
		
		  out = "";
		  len = str.length;
		  i = 0;
		  while(i < len) {
		    c = str.charCodeAt(i++);
		    switch(c >> 4) {
		      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
		        // 0xxxxxxx
		    out += str.charAt(i-1);
		    break;
		  case 12: case 13:
		    // 110x xxxx   10xx xxxx
		    char2 = str.charCodeAt(i++);
		    out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
		    break;
		  case 14:
		    // 1110 xxxx  10xx xxxx  10xx xxxx
		        char2 = str.charCodeAt(i++);
		        char3 = str.charCodeAt(i++);
		        out += String.fromCharCode(((c & 0x0F) << 12) |
		        ((char2 & 0x3F) << 6) |
		        ((char3 & 0x3F) << 0));
		        break;
		    }
		  }
		  return out;
	}
编码
var original = "hello world" ; 
var cipher = utf8to16(atob(original)) ;
解码
var original = btoa(utf16to8(cipher)) ;

3.JAVA中的中文乱码解决方法

编码
String original = "hello world" ;
String cipher = new String(Base64.encode(original .getBytes(StringUtil.__UTF8))) ;
解码
String original = new String(Base64.decode(cipher .getBytes()), StringUtil.__UTF8) ;
经验分享 程序员 微信小程序 职场和发展