java 关于base64中文乱码问题解决 最少操作

前言

使用base64转码中文名称后解码时发现乱码

 截取字符串:{"userName":"冯���城","userId":"124"}

原因

字符串获取字节码默认是 ISO-8859-1

   static byte[] encode(String charsetName, char[] ca, int off, int len)
        throws UnsupportedEncodingException
    {
        StringEncoder se = deref(encoder);
        String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;
        if ((se == null) || !(csn.equals(se.requestedCharsetName())
                              || csn.equals(se.charsetName()))) {
            se = null;
            try {
                Charset cs = lookupCharset(csn);
                if (cs != null)
                    se = new StringEncoder(cs, csn);
            } catch (IllegalCharsetNameException x) {}
            if (se == null)
                throw new UnsupportedEncodingException (csn);
            set(encoder, se);
        }
        return se.encode(ca, off, len);
    }

解决

传入字符串获得字节码时指定字符集 UTF-8
转码

    /**
     * BASE64编码
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(final String str) {
        try {
            if (str == null || "".equals(str)) {
                return "";
            }
            return new String(encryptBASE64(str.getBytes("UTF-8")));
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

解码

  /**
     * BASE64解码
     *
     * @param str
     * @return
     * @throws Exception
     */
    public static String decryptBASE64(final String str) {
        try {
            if (str == null || "".equals(str)) {
                return "";
            }
            return new String(decryptBASE64(str.getBytes("UTF-8")));
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

这样编译出来的东西再转码就没问题

String s = Base64Util.encryptBASE64(o.toString());
--eyJ1c2VyTmFtZSI6IuWGr+WKoOaIkCIsInVzZXJJZCI6IjEyNCJ9
{"userName":"冯加成","userId":"124"}
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值