Java的BASE64 UTF8字符串解码 [英] Java BASE64 utf8 string decoding
本文介绍了Java的BASE64 UTF8字符串解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用org.apache.commons。codec.binary.Base64做去code字符串是UTF8。有时我的base64 EN codeD字符串,之后去code看起来像例如 ^ @k��@@
。我如何检查是否Base64是正确的,或者去codeD UTF8字符串是有效的UTF8字符串?
要澄清。我使用
公共静态字符串base64De code(字符串str){
尝试{
返回新的String(base64De code(str.getBytes(Constants.UTF_8)),Constants.UTF_8);
}赶上(UnsupportedEncodingException五){
...
}
}公共静态的byte [] base64De code(字节[]的字节数组){
返回Base64.de codeBase64(字节阵列);
}
解决方案
您应该转换字符串
到字节[] 时指定字符集code>,反之亦然。
字节[]字节= string.getBytes(UTF-8);
//饲料字节为Base64
和
//从Base64编码字节
串串=新的字符串(字节,UTF-8);
否则该平台的默认编码将使用这不一定是UTF-8本身。
I'm using org.apache.commons.codec.binary.Base64 do decode string which is utf8. Sometimes I get base64 encoded string which after decode looks like for example ^@k��@@
. How can I check if base64 is correct or if decoded utf8 string is valid utf8 string?
To clarify. I'm using
public static String base64Decode(String str) {
try {
return new String(base64Decode(str.getBytes(Constants.UTF_8)), Constants.UTF_8);
} catch (UnsupportedEncodingException e) {
...
}
}
public static byte[] base64Decode(byte[] byteArray) {
return Base64.decodeBase64(byteArray);
}
解决方案
You should specify the charset during converting String
to byte[]
and vice versa.
byte[] bytes = string.getBytes("UTF-8");
// feed bytes to Base64
and
// get bytes from Base64
String string = new String(bytes, "UTF-8");
Otherwise the platform default encoding will be used which is not necessarily UTF-8 per se.
这篇关于Java的BASE64 UTF8字符串解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文