2012-07-06 61 views
0

我的代码:为什么这些对base64类的调用返回不同的结果?

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== 

为什么我得到不同的结果?

回答

2

我认为Hex.encodeHexString将您的编码字符串十六进制编码,而第二个是一个普通的字符串

+0

我应该怎么做才能从apache实现中获得适当的价值? – SuitUp 2012-07-06 10:28:40

+0

我不知道这个库,但尝试仅打印encodeBase64(不使用Hex.encodeHexString)或尝试使用encodeBase64String – nidomiro 2012-07-06 10:33:10

+0

行,它的工作原理,thx。 :) – SuitUp 2012-07-06 10:37:24

2

Base64.encodeBase64()的API文档:

的byte []包含的Base64在他们的UTF字符-8表示。

所以不是

System.out.println(Hex.encodeHexString(encodeBase64)); 

你应该写

System.out.println(new String(encodeBase64, "UTF-8")); 

BTW:你永远不应该使用String.getBytes()版本没有明确的编码,因为结果取决于默认的平台编码(用于Windows这通常是“Cp1252”和Linux“UTF-8”)。

+0

你说得对,thx。 – SuitUp 2012-07-06 11:53:32