这几天做项目时遇到一个问题。我在本地测试base64编码和解码都通过。比如下图。
String str = "我就是我";
String encodeStr = encodeBase64(str.getBytes());
String decodeStr = decodeBase64(encodeStr);
System.out.println("编码前:" + str);
System.out.println("编码后:" + encodeStr);
System.out.println("解码后:" + decodeStr);控制台:
编码前:我就是我
编码后:ztK+zcrHztI=
解码后:我就是我但是同样的代码我同事远程连接传过来的数据却出现乱码。原因是他编码后的结果和我的居然不一样。
使用的都是commons-codec1.6.jar包。项目都是UTF-8的环境。
怀疑与环境有关!我用UTF-8硬编码后才正常!请高手帮忙看看!
String str = "我就是我";
String encodeStr = encodeBase64(str.getBytes());
String decodeStr = decodeBase64(encodeStr);
System.out.println("编码前:" + str);
System.out.println("编码后:" + encodeStr);
System.out.println("解码后:" + decodeStr);控制台:
编码前:我就是我
编码后:ztK+zcrHztI=
解码后:我就是我但是同样的代码我同事远程连接传过来的数据却出现乱码。原因是他编码后的结果和我的居然不一样。
使用的都是commons-codec1.6.jar包。项目都是UTF-8的环境。
怀疑与环境有关!我用UTF-8硬编码后才正常!请高手帮忙看看!
byte[] getBytes(String charsetName)使用这两个,不要使用无参数的
/**
* Encodes this {@code String} into a sequence of bytes using the
* platform's default charset, storing the result into a new byte array.
*
* <p> The behavior of this method when this string cannot be encoded in
* the default charset is unspecified. The {@link
* java.nio.charset.CharsetEncoder} class should be used when more control
* over the encoding process is required.
*
* @return The resultant byte array
*
* @since JDK1.1
*/
public byte[] getBytes() {
return StringCoding.encode(value, offset, count);
}如果你是XP的话 那你的默认编码是GB18030getBytes() 使用带参方法
/**
* BASE标准解码
*
* @author lz
* @param buff
* @return
*/
public static String decodeBase64(String str) {
return str == null ? null : StringUtils.newStringUtf8(base64.decode(str));
} /**
* BASE64 编码
*
* @param s
* @return
*/
public static String encodeBufferBase64(byte[] buff) {
return buff == null ? null : encoder.encodeBuffer(buff).trim();
}