微信小程序中使用emoji表情

【问题描述】

    微信小程序开发,商户授权给用户后,用户便可关注小程序。有的用户的微信账户号中带有emoji表情,这样的话,直接存储到mysql5.5以下版本的数据库中会报异常。项目中的mysql数据库的版本是5.1.8的。

【问题缘由】

    emoji是4个字节的,因为编码方式不同,所以如果将emoji表情直接存入utf8编码的数据库,会报错,存不进去。

【解决方案】

    一. 修改数据库编码方式(mysql的版本必须为v5.5.3或更高)
        1. 把数据库的编码改成utf8mb4 – UTF-8 Unicode
        2. 将需要存储emoji表情的字段选择utf8mb4_general_ci
        3. 数据库连接也需要改为utf8mb4
    设置完成后,应该可以看到如下类似字符集设置结果。那么可以直接的存入数据库,无需做任何额外的事情了。

微信小程序中使用emoji表情_第1张图片

    二. 存之前base64_encode(),取的时候base64_decode()
        1. 采用的是Apache Commons Codec作法,Apache Commons Codec有提供Base64的编码与解码功能,会使用到org.apache.commons.codec.binary套件下的Base64类别,用法如下:
final Base64 base64 = new Base64();
final String text = "字串文字";
final byte[] textByte = text.getBytes("UTF-8");
//编码
final String encodedText = base64.encodeToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(base64.decode(encodedText), "UTF-8"));
        2. Java 8之后的作法,Java 8的java.util中,新增了Base64的类别,可以用来处理Base64的编码与解码,用法如下:
final Base64.Decoder decoder = Base64.getDecoder();
final Base64.Encoder encoder = Base64.getEncoder();
final String text = "字串文字";
final byte[] textByte = text.getBytes("UTF-8");
//编码
final String encodedText = encoder.encodeToString(textByte);
System.out.println(encodedText);
//解码
System.out.println(new String(decoder.decode(encodedText), "UTF-8"));

你可能感兴趣的:(#,UQI)