在我们开发的过程中出现中文乱码是经常可能出现的问题,但是解决方法也各种各样,在此总结一下解决方法和各种方法中可能出现的问题
一、将字节数组进行相应的编码
String str = "我是一段中文Code";
//1、使用默认的字符编码 ,注意Charset.defaultCharset()的编码格式由系统默认的语言决定,中国默认的是GBK编码
String message = new String(str.getBytes(), Charset.defaultCharset());
//不指定编码格式,默认使用的就是Charset.defaultCharset()
String message = new String(str.getBytes());
//2、指定具体的字符编码
String message = new String(str.getBytes(), "UTF-8");
//3、根据传入的编码格式解析后转成指定字符编码
String message = new String(str.getBytes("GBK"), "UTF-8");
二、对传输数据进行UTF-8编码和解码
String str = "我是一段中文Code";
//进行UTF-8编码
String utf8Msg = URLEncoder.encode(str , "UTF-8");
//对字符进行UTF-8解码
String message = URLDecoder.decode(utf8Msg ,"UTF-8");
注意:在解码的过程中,如果参数中存在%时,解码会出现一下异常
- Exception in thread "main" java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "u9"
- at java.net.URLDecoder.decode(URLDecoder.java:194)
- at com.hbzx.controller.PayResultController.main(PayResultController.java:253)
解决办法:使用%25替换字符串中的%号
utf8Msg = utf8Msg .replaceAll("%(?![0-9a-fA-F]{2})", "%25");
String message = URLDecoder.decode(utf8Msg ,"UTF-8");