【发布时间】:2012-03-07 20:42:06
【问题描述】:
我正在尝试使用 sun.misc.BASE64Encoder/Decoder,但是这段代码:
(new sun.misc BASE64Encoder()).encode(new
sun.misc.BASE64Decoder().decodeBuffer("test string XML:"))
返回“测试/字符串/XML/” 我很尴尬
【问题讨论】:
标签: java
我正在尝试使用 sun.misc.BASE64Encoder/Decoder,但是这段代码:
(new sun.misc BASE64Encoder()).encode(new
sun.misc.BASE64Decoder().decodeBuffer("test string XML:"))
返回“测试/字符串/XML/” 我很尴尬
【问题讨论】:
标签: java
不要使用sun.misc 或com.sun 类。不保证它们在不同版本的 jre 之间保持一致。
使用commons-codecBase64.encodeBase64(..)和Base64.decodeBase64(..)
【讨论】:
使用类:
javax.xml.bind.DatatypeConverter
它有 2 种有趣的方法:
public static byte[] parseBase64Binary( String lexicalXSDBase64Binary )
public static String printBase64Binary( byte[] val )
【讨论】:
您首先解码字符串“test string XML:”,它不是真正有效的 Base64,因为它包含空格和冒号,它们都不是有效的 B64 字符。我认为你的意思是先编码然后解码,像这样:
(new sun.misc.BASE64Decoder().decodeBuffer(new sun.misc.BASE64Encoder().encode("test string XML:"))
【讨论】:
我想你想要:
String s = "Hello world";
new sun.misc.BASE64Encoder().encode(s.getBytes("UTF-8"));
更好的是,按照前面的答案建议使用 commons utils。如果您不能在另一个 jar 上添加外部依赖,请仅使用 sun.misc.Base64Encoder。
【讨论】: