日期:2014-05-20  浏览次数:20923 次

两台机器Base64编码出现不同的结果!求助!
这几天做项目时遇到一个问题。我在本地测试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硬编码后才正常!请高手帮忙看看!

------解决方案--------------------
问题估计在getBytes!
------解决方案--------------------
探讨

问题估计在getBytes!

------解决方案--------------------
byte[] getBytes(Charset charset)
byte[] getBytes(String charsetName)

使用这两个,不要使用无参数的
------解决方案--------------------
同意3楼的。
------解决方案--------------------
Java code

    /**
     * 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);
    }