Java 为什么对base64类的调用会返回不同的结果?
我的代码:Java 为什么对base64类的调用会返回不同的结果?,java,base64,Java,Base64,我的代码: private static String convertToBase64(String string) { final byte[] encodeBase64 = org.apache.commons.codec.binary.Base64.encodeBase64(string .getBytes()); System.out.println(Hex.encodeHexString(encodeBas
private static String convertToBase64(String string)
{
final byte[] encodeBase64 =
org.apache.commons.codec.binary.Base64.encodeBase64(string
.getBytes());
System.out.println(Hex.encodeHexString(encodeBase64));
final byte[] data = string.getBytes();
final String encoded =
javax.xml.bind.DatatypeConverter.printBase64Binary(data);
System.out.println(encoded);
return encoded;
}
现在我称之为:convertToBase64(“stackoverflow”)编码>并得到以下结果:
6333526859327476646d56795a6d787664773d3d
c3RhY2tvdmVyZmxvdw==
为什么我会得到不同的结果?我认为Hex.encodeHexString会将您的字符串编码为hexcode,第二个是普通字符串我认为Hex.encodeHexString会将您的字符串编码为hexcode,第二个是来自Base64.encodeBase64()的API文档的普通字符串:
字节[],在UTF-8表示形式中包含Base64字符
所以相反
System.out.println(Hex.encodeHexString(encodeBase64));
你应该写
System.out.println(new String(encodeBase64, "UTF-8"));
顺便说一句:在没有显式编码的情况下,永远不要使用String.getBytes()
版本,因为结果取决于默认的平台编码(对于Windows,这通常是“Cp1252”和Linux“UTF-8”)。来自Base64.encodeBase64()的API文档:
字节[],在UTF-8表示形式中包含Base64字符
所以相反
System.out.println(Hex.encodeHexString(encodeBase64));
你应该写
System.out.println(new String(encodeBase64, "UTF-8"));
顺便说一句:在没有显式编码的情况下,永远不要使用String.getBytes()
版本,因为结果取决于默认的平台编码(对于Windows,这通常是“Cp1252”和Linux“UTF-8”)。我应该怎么做才能从apache实现中获得正确的值?我不知道这个库,但尝试只打印encodeBase64(不带Hex.encodeHexString)或尝试使用EncodeBase64Strings如何从apache实现中获得正确的值?我不知道这个库,但尝试只打印encodeBase64(不带Hex.encodeHexString)或尝试使用EncodeBase64Strings