什么GBK,UTF-8都是浮云,乱码得这样。[Base64加密解密]

时间:2022-12-03 00:03:14

相信很多人都会遇到乱码问题。想我当初遇到乱码时也是这里转那边转,配置文件里面改,服务器配置里面改,还用强转,改来改去最后还是乱码。

烦死人了。这不。最近又乱码了。好在上天有好生之德。让土豆我意外知道一个东西。哟呵呵~~~解决乱码不是问题。那就是使用Base64编码,接收时再转码。保证不会出现乱码的问题。为什么?这还用说,base64转码后就不是中文了,而是全英文的~~~不多说了。程序员别的不会,先贴代码。

private static BASE64Encoder encoder = new BASE64Encoder();
private static BASE64Decoder decoder = new BASE64Decoder();
/**
* BASE64 编码
*
* @param s
* @return
*/
public static String encodeBufferBase64(byte[] buff)
{
return buff == null?null:encoder.encodeBuffer(buff).trim();
}


/**
* BASE64解码
*
* @param s
* @return
*/
public static byte[] decodeBufferBase64(String s)
{
try
{
return s == null ? null : decoder.decodeBuffer(s);
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}


/**
* base64编码
*
* @param bytes
* 字符数组
* @return
* @throws IOException
*/
public static String encodeBytes(byte[] bytes) throws IOException
{
return new BASE64Encoder().encode(bytes).replace("\n", "").replace("\r", "");
}

/**
* base64解码
*
* @param bytes
* 字符数组
* @return
* @throws IOException
*/
public static String decodeBytes(byte[] bytes) throws IOException
{
return new String(new BASE64Decoder().decodeBuffer(new String(bytes)));
}

测试代码如下:

public static void main(String[] args) throws Exception
{
String str1="我爱你";
String s=encodeBufferBase64(str1.getBytes());
System.out.println(s);
String strs=new String(decodeBufferBase64(s));
System.out.println(strs);
}


控制台显示:

ztKwrsTj
我爱你


上面有2种方法编码和解码。只不过第二种去掉了空格。

按需分配。Over~~~