最近在做一个APP,第三方登录的时候昵称表情存储报错,
Caused by: java.sql.SQLException: Incorrect string value: '\xF0\x9F\x98...' for column 'nick_name' at row 1
我对数据库的编码,表格的编码,字段的编码,my.ini配置文件都进行了修改,将utf8改成了utf8mb4,还是不行,所以我放弃了这种方式,取而代之的有如下两种方案
1.在存值取值的时候做处理
import org.apache.commons.codec.binary.Base64;
public String getNickname() {
try {
nickName = new String(Base64.decodeBase64(nickname), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return nickName;
}
public void setNickname(String nickname) {
try {
nickname = Base64.encodeBase64String(nickname.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
this.nickname = nickname;
}
2.没办法的办法,将所有Emoji过滤成其他字符
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @Description
* @Author zk
* @createTime 2018/12/14 10:00
*/
public class EmojiUtil {
public static String filterEmoji(String nick_name) {
//nick_name 所获取的用户昵称
if (nick_name == null) {
return nick_name;
}
Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
Matcher emojiMatcher = emoji.matcher(nick_name);
if (emojiMatcher.find()) {
//将所获取的表情转换为*
nick_name = emojiMatcher.replaceAll("(表情)");
return nick_name;
}
return nick_name;
}
}
希望能够帮到大家