两台机器Base64编码出现不同的结果!求助!

yaerfeng 2011-12-28 05:21:35
这几天做项目时遇到一个问题。我在本地测试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硬编码后才正常!请高手帮忙看看!
...全文
779 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yaerfeng 2011-12-29
  • 打赏
  • 举报
回复
问题解决。原因是JDK版本的问题。然后加上楼上几位的见解,查看了commons-codec的源码。问题解决。把代码贴下这里。后者如有人出现类似问题。可以参考。
/**
* 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();
}
meran 2011-12-28
  • 打赏
  • 举报
回复

/**
* 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的话 那你的默认编码是GB18030

getBytes() 使用带参方法
johnswood 2011-12-28
  • 打赏
  • 举报
回复
同意3楼的。
huntor 2011-12-28
  • 打赏
  • 举报
回复
byte[] getBytes(Charset charset)
byte[] getBytes(String charsetName)

使用这两个,不要使用无参数的
soli11722984 2011-12-28
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 healer_kx 的回复:]

问题估计在getBytes!
[/Quote]
+1
healer_kx 2011-12-28
  • 打赏
  • 举报
回复
问题估计在getBytes!

62,634

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧