在开发中产品允许用户输入中文是一件很头疼的事,不同地方产生的请求传过来的中文字符可能编码不同,存到数据库都变成了可爱的乱码,所以必须先把它转成统一的编码格式,how?
public static String getUTFStringByEncoding(String str) {
String encode = "UTF-8";
String returnStr = "";
try {
if(str!=null){
if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
encode = "GB2312";
}else if (str.equals(new String(str.getBytes("ISO-8859-1"), "ISO-8859-1"))) {
encode = "ISO-8859-1";
}else if (str.equals(new String(str.getBytes("UTF-8"), "UTF-8"))) {
encode = "UTF-8";
}else if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
encode = "GBK";
}
if(encode.equals("UTF-8")){
returnStr = str;
}else{
returnStr = new String(str.getBytes(encode),"UTF-8");
}
}
} catch (Exception ex) {
log.error( ex.getMessage());
ex.printStackTrace();
}
return returnStr;
}
不知道原来的编码,拿到的bytes可能是不同的,所以先判断原来的编码是必要的。